gpt4 book ai didi

c - 使用不包含头文件的 C 结构

转载 作者:太空狗 更新时间:2023-10-29 15:53:38 29 4
gpt4 key购买 nike

我的基本问题是我想通过在我的代码中不包含头文件来使用头文件中定义的一些结构和函数。

头文件由工具生成。由于我无权访问头文件,因此无法将其包含在我的程序中。

这是我的场景的一个简单示例:

先.h

#ifndef FIRST_H_GUARD
#define FIRST_H_GUARD
typedef struct ComplexS {
float real;
float imag;
} Complex;

Complex add(Complex a, Complex b);

// Other structs and functions
#endif

先.c

#include "first.h"

Complex add(Complex a, Complex b) {
Complex res;
res.real = a.real + b.real;
res.imag = a.imag + b.imag;
return res;
}

我的程序.c

// I cannot/do not want to include the first.h header file here
// but I want to use the structs and functions from the first.h
#include <stdio.h>

int main() {
Complex a; a.real = 3; a.imag = 4;
Complex b; b.real = 6; b.imag = 2;

Complex c = add(a, b);
printf("Result (%4.2f, %4.2f)\n", c.real, c.imag);

return 0;
}

我的意图是为 my_program 构建一个目标文件,然后使用链接器将目标文件链接到可执行文件中。我想在 C 中实现什么?

最佳答案

为了使用 my_program.c 中的结构,必须在 my_program.c定义该结构。没有办法解决它。

为了定义它,您必须包含 first.h 或在 my_program.c 中提供 Complex 的定义其他方式(比如将 Complex 的定义复制粘贴到 my_program.c 中)。

如果您的 first.h 看起来和您发布的一样,那么当然没有必要进行任何复制粘贴,因为无论如何它都是一样的。只需包含您的 first.h

如果您不想包含 first.h 因为该 header 中有其他内容(您未在此处显示),您可以移动 Complex 的定义code> 到一个单独的小标题中,并将其包含在两个地方。

关于c - 使用不包含头文件的 C 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2959691/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com