【发布时间】:2019-07-16 08:56:17
【问题描述】:
我需要访问在 c++ 文件中的 c 文件头中定义的结构的内容。
头文件struct.h目前具有以下格式:
typedef struct {
int x;
int y;
} structTypeName;
extern structTypeName structName;
结构体在文件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";
}
}
【问题讨论】:
-
可能您所需要的只是在您的
struct.h文件中添加extern "C" {...},或者,如果这在您周围是不可能的#include "struct.h" -
我已经通过
extern "C" {}包含了struct.h。我仍然无法访问变量的值。在我的想象中,像var = structName.x这样的东西应该足以做到这一点 -
@KBS 请添加您尝试访问结构的 C++ 代码示例。看源码会更容易发现问题。
-
如果您混合使用 C 和 C++ 代码,您的
main函数应该在 C++ 代码中。