我想从 dll 导出一个全局变量,我定义了如下所示的全局变量。假设这个变量是在A.cpp中定义的
extern "C" __declspec(dllexport) int A;
同时,在dll中,另一个源文件B.cpp想要使用并修改这个值。我想知道如何在使用之前在 B.cpp 中声明该变量。
extern "C" int A; ?
如果在这种情况下,编译如何识别声明和定义?
extern extern "C" 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”
block ,只不过声明的实体具有 C 链接而不是 C++ 链接。
extern "C" {
int A;
extern int B = 0;
extern int C;
}
关于c++ - 如何 extern 声明 extern "C"变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66105635/