我在 Windows 7 Pro 64 位上使用 mingw-w64。在尝试访问外部变量时,在经历了很多头发撕裂之后,我终于得出了这个结论:
// MultiTest2.h
// Version 1.0.0
// MDJ 2016/04/13
#ifndef MULTITEST2_H
#define MULTITEST2_H
extern "C" {
int iXfer;
int setInt();
}
#endif // MULTITEST2_H
不起作用(我正在使用'extern "C"'而不只是'extern',因为我正在努力最终链接到汇编代码),但是:
// MultiTest2.h
// Version 1.0.1
// MDJ 2016/04/13
#ifndef MULTITEST2_H
#define MULTITEST2_H
extern "C" int iXfer;
extern "C" int setInt();
#endif // MULTITEST2_H
有效!
仅供引用,系统中的其他两个文件是:
// MultiTest2.cpp
// Version 1.0.0
// MDJ 2016/04/13
#include "MultiTest2.h"
int iXfer = 0;
int setInt() {
iXfer = 6253;
return 0;
}
和:
// MultiTest1.cpp
// Version 1.0.0
// MDJ 2016/04/13
#include <iostream>
#include "MultiTest2.h"
using namespace std;
int main() {
setInt();
cout << iXfer << endl;
}
对于 MultiTest2.h 的 1.0.0 版('extern "C"' block 中的声明),输入后立即:
g++ -S MultiTest2.cpp
结果是:
MultiTest2.cpp:7:5: error: redefinition of 'int iXfer'
int iXfer = 0;
^
In file included from MultiTest2.cpp:5:0:
MultiTest2.h:12:6: note: 'int iXfer' previously declared here
int iXfer;
^
但是,对于 MultiTest2.h 的 1.0.1 版(单独的“extern“C””声明),以下序列可以完美运行:
c:\work\gccWork\MultiTest>g++ -S MultiTest2.cpp
c:\work\gccWork\MultiTest>g++ -S MultiTest1.cpp
c:\work\gccWork\MultiTest>g++ -c MultiTest2.s
c:\work\gccWork\MultiTest>g++ -c MultiTest1.s
c:\work\gccWork\MultiTest>g++ -o MultiTest.exe MultiTest2.o MultiTest1.o
c:\work\gccWork\MultiTest>MultiTest
6253
这是某种 mingw-w64 特性,还是我在这里遗漏了什么?
最佳答案
它们不一样。
extern "C" int foo;
做两件事:它声明 foo 是外部的(即这只是一个声明,符号将由另一个模块定义),它声明 foo 的链接为“C”,这会影响符号名称。
另一方面,
extern "C" {
int foo;
}
仅声明 foo 具有 C 链接。它没有将符号声明为 extern,这意味着这是一个定义,而不仅仅是一个声明。
换句话说
extern "C" int foo;
与(注意extern关键字的重复)相同
extern "C" {
extern int foo;
}
关于c++ - 从另一个文件访问 C++ 中的 extern "C"变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36609147/