Reputation: 1615
I have a frequently used function f()
. I want f()
to be in header file util.h
, so that I can use f()
easily without any extra compilation:
user1.c
:
#include "util.h"
int main(){
f();
return 0;
}
util.h
:
void f(){
// do some job
}
Compilation of user1.c
:
gcc -o user1 user1.c
The problem occurs when there are two compilation units unit2.o
and unit3.o
. Their source codes are as follows:
user2.c
:
#include "util.h"
void user2_function(){
f();
// do other jobs
}
user3.c
:
#include "util.h"
extern void user2_function();
int main(){
f();
user2_function();
return 0;
}
I get multiple definition of f
error when I try to compile these source codes as follows:
gcc -c user2.c
gcc -c user3.c
gcc -o user user2.o user3.o
Question is how the multiple definition
problem can be solved? Or are there any better solutions?
In the real case, there are hundreds of functions in util.h
and there are about 50 different compilation units.
I am trying to avoid using a library and the compilation step of utility functions since:
cmake
, etc.Upvotes: 2
Views: 5903
Reputation: 48087
Change util.h
to be util.c
And use a new util.h
that contains
void f();
instead.
Upvotes: 2
Reputation: 6578
You are actually specifying the body of the function in the header file. Therefore object code will be emitted for it into both object files, which is not allowed/valid.
To rectify this either:
inline
Upvotes: 7