4
votes

I have a base Core.h file and many other .cpp and .h files, lets say - (a.cpp, a.h, b.cpp, b.h, c.cpp, c.h)

Now, I have included Core.h file in all .h files (i.e. a.h, b.h and c.h) . And in c.cpp, I am including a.h and b.h file. As a result Core.h file is getting included two times and I am getting error of kind

/tmp/ccq7z6jY.o: In function `fileID2fileName(int)':
/home/Core.h:20: multiple definition of `fileID2fileName(int)'
/tmp/cciNkoqe.o:/home/Core.h:20: first defined here
/tmp/ccravW4I.o: In function `fileID2fileName(int)':
/home/Core.h:20: multiple definition of `fileID2fileName(int)'
/tmp/cciNkoqe.o:/home/Core.h:20: first defined here
/tmp/ccdUjOEu.o: In function `fileID2fileName(int)':
/home/Core.h:20: multiple definition of `fileID2fileName(int)'
/tmp/cciNkoqe.o:/home/Core.h:20: first defined here
collect2: ld returned 1 exit status
1
Include guards will not fix functions defined in a header having multiple definitions within a program. There's nothing stopping two separate TUs from both including the header and then being linked. You must either give the function internal linkage or define it in an implementation file.chris
@chris: That's an answer; please make it one!Lightness Races in Orbit

1 Answers

14
votes

The problem is not include guards : they won't help across different translation units.

You need to either :

  • define your functions one time each in a .cpp file and only declare them in your .h file
  • define them inline in your headers
  • define them static in your headers

As StackedCrooked rightly mentions, including the static function definition but not using it will result in an appropriate compiler warning.