如何 extern 声明一个 extern "C" 变量
How to extern declare an extern "C" variable
我想从 dll 导出一个全局变量我定义了如下的全局变量。假设这个变量定义在 A.cpp
extern "C" __declspec(dllexport) int A;
同时,在dll中,另一个源文件B.cpp想要使用和修改这个值。我想知道如何在使用它之前在 B.cpp 中声明变量。
extern "C" int A; ?
如果在这种情况下,编译如何识别declare和definition?
extern extern "C" int A; ?
肯定是格式错误。
extern extern "C" int A; ?
extern "C"
可以作为一个块:
extern "C"
{
extern int A;
}
根据 [basic.def]/2.2,名称空间范围内的对象声明是一个定义,除非:
it contains the extern
specifier (9.2.1) or a linkage-specification19 (9.11) and neither an initializer nor a function-body,
...
19 Appearing inside the brace-enclosed declaration-seq in a linkage-specification does not affect whether a declaration is a definition.
因此:
extern "C" int A;
是声明。
extern "C" int A = 0;
是一个定义。
下面定义了 A
和 B
,并声明了 C
:效果与没有 extern "C"
块的效果相同,除了实体声明有 C 链接而不是 C++ 链接。
extern "C" {
int A;
extern int B = 0;
extern int C;
}
声明需要像A.h一样在header文件中,否则其他代码文件不能使用它。如果没有 header 文件,dllexport 尤其没用。您可能需要某种 DLLEXPORT 宏,以便可以根据需要将其定义为 dllexport 和 dllimport。查看几乎任何 Windows DLL 代码。
然后在 cpp 文件中包含 header。这允许您的代码使用声明为 extern
.
的变量
在 one 的 cpp 文件中包含 header AND 然后使用相同的类型和名称定义变量没有外部。然后链接器会将它的数据存储放入与该 cpp 文件的其余部分相同的模块中,并且该名称的所有其他用途都链接到该定义。
但是,就像 C++ 中的私有成员变量一样,在 DLL 中公开全局变量是个坏主意。将对它们的访问隐藏在函数调用后面要好得多。
我想从 dll 导出一个全局变量我定义了如下的全局变量。假设这个变量定义在 A.cpp
extern "C" __declspec(dllexport) int A;
同时,在dll中,另一个源文件B.cpp想要使用和修改这个值。我想知道如何在使用它之前在 B.cpp 中声明变量。
extern "C" int A; ?
如果在这种情况下,编译如何识别declare和definition?
extern extern "C" int A; ?
肯定是格式错误。
extern extern "C" int A; ?
extern "C"
可以作为一个块:
extern "C"
{
extern int A;
}
根据 [basic.def]/2.2,名称空间范围内的对象声明是一个定义,除非:
it contains the
extern
specifier (9.2.1) or a linkage-specification19 (9.11) and neither an initializer nor a function-body,
...
19 Appearing inside the brace-enclosed declaration-seq in a linkage-specification does not affect whether a declaration is a definition.
因此:
extern "C" int A;
是声明。
extern "C" int A = 0;
是一个定义。
下面定义了 A
和 B
,并声明了 C
:效果与没有 extern "C"
块的效果相同,除了实体声明有 C 链接而不是 C++ 链接。
extern "C" {
int A;
extern int B = 0;
extern int C;
}
声明需要像A.h一样在header文件中,否则其他代码文件不能使用它。如果没有 header 文件,dllexport 尤其没用。您可能需要某种 DLLEXPORT 宏,以便可以根据需要将其定义为 dllexport 和 dllimport。查看几乎任何 Windows DLL 代码。
然后在 cpp 文件中包含 header。这允许您的代码使用声明为 extern
.
在 one 的 cpp 文件中包含 header AND 然后使用相同的类型和名称定义变量没有外部。然后链接器会将它的数据存储放入与该 cpp 文件的其余部分相同的模块中,并且该名称的所有其他用途都链接到该定义。
但是,就像 C++ 中的私有成员变量一样,在 DLL 中公开全局变量是个坏主意。将对它们的访问隐藏在函数调用后面要好得多。