使用C struct而不包含头文件

sha*_*ams 3 c struct external header-files

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

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

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

first.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
Run Code Online (Sandbox Code Playgroud)

first.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;
}
Run Code Online (Sandbox Code Playgroud)

my_program.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;
}
Run Code Online (Sandbox Code Playgroud)

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

AnT*_*AnT 7

为了在使用该结构my_program.c,该结构必须被限定my_program.c.没有办法绕过它.

为了定义它,你必须以其他方式包含first.h或提供Complexin 的定义my_program.c(比如复制粘贴Complexinto 的定义my_program.c).

如果first.h你发布了你的外观,那么进行任何复制粘贴都没有意义,当然,因为它无论如何都是一样的.只包括你的first.h.

如果您不希望包含first.h该标题中的其他内容(此处未显示),则可以将定义移动Complex到单独的小标题中,并将其包含在两个位置.

  • @shams:你*需要*那些结构和函数的定义.编译器不知道该怎么做.对于函数,编译器可以猜测,但通常猜测很糟糕并导致代码损坏. (5认同)
  • 如果你的函数指向结构,你可以将它们拆分成一个单独的头,并在那里向前声明结构(typedef struct ComplexS Complex;).你将无法查看main()中结构的内容,但至少你可以调用这些函数. (2认同)