Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent multiple definitions of functions from .h file

Tags:

c++

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
like image 671
user3747190 Avatar asked Dec 09 '22 06:12

user3747190


1 Answers

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.

like image 193
Quentin Avatar answered Apr 13 '23 01:04

Quentin