在linux下写一个c语言的头文件.h,其中有一个结构体变量是引用另外一个C++的.h文件中定义的枚举变量,使用extern c使得能够编译通过这个.c文件
时间: 2024-02-27 15:53:35 浏览: 130
可以按照以下步骤编写头文件:
1. 在头文件中包含需要引用的C++头文件,并使用extern "C"包裹起来,表示使用C语言的编译方式。
```c
#ifdef __cplusplus
extern "C" {
#endif
#include "other_cpp_header.h"
typedef struct {
enum Color color;
int size;
} MyStruct;
#ifdef __cplusplus
}
#endif
```
2. 在C++头文件中定义枚举变量:
```cpp
// other_cpp_header.h
enum Color {
RED,
GREEN,
BLUE
};
```
3. 在C文件中包含上述头文件,然后使用MyStruct结构体变量即可:
```c
#include "my_header.h"
int main() {
MyStruct s;
s.color = RED;
s.size = 10;
return 0;
}
```
编译时需要先将C++头文件编译成目标文件,然后再将C文件和目标文件链接起来:
```bash
g++ -c other_cpp_header.h -o other_cpp_header.o
gcc main.c other_cpp_header.o -o main
```
阅读全文
相关推荐
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)