Kadir
Kadir

Reputation: 1615

Avoid multiple definition due to inclusion of same header file in case of multiple compilation units

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:

  1. There are many different platforms that I use.
  2. I wonder if there is a simple solution, i.e., without using cmake, etc.
  3. I also use cross compilation for coprocessors.
  4. I want the flags used in compilation of the utility functions to be same as the flags used in compilation of user codes.

Upvotes: 2

Views: 5903

Answers (2)

WiSaGaN
WiSaGaN

Reputation: 48087

Change util.h to be util.c

And use a new util.h that contains

void f(); 

instead.

Upvotes: 2

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:

  • Mark the function inline
  • Place only a forward declaration of the function in the header file, and specify the body in a separate source code file, which you then compile along with your other source code files

Upvotes: 7

Related Questions