我需要访问在 C++ 文件中的 C 文件 header 中定义的结构的内容。
头文件 struct.h
当前具有以下格式:
typedef struct {
int x;
int y;
} structTypeName;
extern structTypeName structName;
struct在文件A.c
中使用和修改
#include "struct.h"
structTypeName structName;
int main(){
structName.x = xyz;
structName.y = zyx;
}
我现在需要访问 C++ 文件 B.cpp
中的结构(是的,它必须是 C++)。我已经尝试了很多不同的想法,但到目前为止还没有任何结果。有人可以告诉我如何实现这一点吗?
编辑:
C++ 文件看起来如下 atm:
#include <iostream>
extern "C"{
#include "struct.h"
}
int main(){
while(true){
std::cout << structName.x << "\n";
}
}
最佳答案
我没有看到您遇到的真正问题。但为了使示例正常工作,我进行了以下更改。
在空调中:
#include "struct.h"
structTypeName structName;
int c_main(void) { // new name since we can't have two "main" functions :-)
structName.x = 123; // settings some defined values
structName.y = 321;
}
在 B.cpp 中:
#include <iostream>
#include "struct.h" // this declares no functions so extern "C" not needed
extern "C" int
c_main(void); // renamed the C-main to c_main and extern declaring it here
int main() {
c_main(); // call renamed C-main to initialize structName.
// and here we go!
while (true) std::cout << structName.x << "\n";
}
最后编译、链接(使用 C++ 编译器)和运行:
$ gcc -c A.c -o A.o
$ g++ -c B.cpp -o B.o
$ g++ A.o B.o -o a.out
$ ./a.out
关于c++ - 在 C++ 中访问 C 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57053584/