c++ - 在 C++ 中访问 C 结构

标签 c++ c struct

我需要访问在 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/

相关文章:

c++ - ptr to c++ source for a simple mac (cocoa) based console to use as a command interpreter

c++ - Online Compiler - 在等待输入时拦截程序并自动输入

c - 为什么不在我的代码中添加#include<linux/sched.h>,代码无法识别 task_struct 结构

c - 了解 C 字符串连接

c - 如何在 C 中修改共享内存(shmget/shmat)?

c++ - 直接初始化中的转换运算符

C++ 程序在条件为 false 之前退出循环

c - scanf 使用 %f 表示整数

c++ - 结构的前向声明不起作用 - 无法弄清楚为什么

c# - 具有引用类型和 GC 的结构?