c++ - 如何 extern 声明 extern "C"变量

标签 c++ dll

我想从 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; 是一个定义。

下面定义了AB,并声明了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/

相关文章:

c# - 如何使用 c# 中未注册的 dll?

c# - 类库命名空间层次结构不起作用

c++ - 使用 C++ 异常的内存泄漏

c++ - qt qgraphicsscene线子类

c++ - 在 C++ 流中禁用指针输出?

delphi - 在使用包编译的 dll 和不使用包编译的 dll 之间处理回调方法是否安全(Delphi)?

将另一个 DLL 链接到项目后,C++ DLL 加载失败

multithreading - 可以强制释放Delphi threadvar内存吗?

c++ - ifstream 管道和多个(顺序)编写器

c++ - 检查所有使用的 OpenGL 扩展