4

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
Slava
  • 43,454
  • 1
  • 47
  • 90
user3747190
  • 1,627
  • 3
  • 20
  • 28
  • 6
    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 Aug 20 '14 at 14:55
  • 1
    @chris: That's an _answer_; please make it one! – Lightness Races in Orbit Aug 20 '14 at 15:08

1 Answers1

14

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.

Quentin
  • 62,093
  • 7
  • 131
  • 191
  • Defining them as `static` might trigger a "unused function" compiler warning though (in the compilation units where its unused). – StackedCrooked Aug 20 '14 at 15:01