【问题标题】:accessing c-struct in c++在 c++ 中访问 c​​-struct
【发布时间】: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++ 代码中。

标签: c++ c struct


【解决方案1】:

我看不出您遇到的真正问题。但为了使示例工作,我做了以下更改。

在交流中:

#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

【讨论】:

    猜你喜欢
    • 2013-09-24
    • 2012-03-08
    • 2016-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-29
    相关资源
    最近更新 更多