My basic problem is that I want to use some structs and functions defined in a header file by not including that header file in my code.
The header file is generated by a tool. Since I don’t have access to the header file, I can’t include it in my program.
Here’s a simple example of my scenario:
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
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;
}
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;
}
My intention is to build an object file for my_program and then use the linker to link up the object files into an executable. Is what I want to achieve possible in C?
In order to use the struct in
my_program.c, the struct has to be defined inmy_program.c. There’s no way around it.In order to define it, you have to either include
first.hor provide a definition ofComplexinmy_program.cin some other way (like copy-paste the definition ofComplexintomy_program.c).If your
first.hlooks as you posted, then there’s no point in doing any copy-pasting, of course, since it is going to be the same thing anyway. Just include yourfirst.h.If you don’t want to include
first.hbecause of something else in that header (which you don’t show here), you can move the definition ofComplexinto a separate small header, and include it instead in both places.