2

i have a file named functions.h....now i know that it is not wise to define functions in the header files but that is least of my concern as compared to the problem which cropped up...

i defined a function in a functions.h named

 void sayhi()
{
  cout<<"hi";
}

now i made a lines.h file whose functions were defined in lines.cpp file...in lines.cpp file i included functions.h...and used sayhi(); in the constructor of lines class...then in mymain.cpp(containing int main) i again included functions.h and in the main i called sayhi();

but when i compiled the program it showed an error in mymain.cpp telling that sayhi() has already been defined in lines.obj...can u point out what am i doing wrong??

AvinashK
  • 3,309
  • 8
  • 43
  • 94
  • About the wiseness of implementations in headers, see this question http://stackoverflow.com/questions/1001639/coding-c-without-headers-best-practices and in particular my answer http://stackoverflow.com/questions/1001639/coding-c-without-headers-best-practices/1001749#1001749. – Daniel Daranas Sep 27 '11 at 10:31
  • that problem is exactly WHY you should not _define_ (aka. implement) a function in a header file... – Adrien Plisson Sep 27 '11 at 10:37

2 Answers2

7

Well, the solution is to declare the function in functions.h and then define it in functions.cpp, the way nature intended.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • @david...okay but i have one more problem....if we declare a template class in header files and define it in the .cpp file and then if we include the header file in the main(containing int main) file then why does a linker error crop up... and the error does not crop up if we included the .cpp file(containing the header file ) in the main file... – AvinashK Sep 27 '11 at 15:28
  • @avinash Ask that as a new question. Comments are not appropriate for asking brand new questions. – David Heffernan Sep 27 '11 at 15:47
  • @DavidHeffernan...i could but recently stackoverflow rejects a question if it is not upto a certain length as a question not upto its quality....so one line questions cant be asked!!! – AvinashK Sep 27 '11 at 18:45
  • If it's too short just pad it with an HTML comment `` or include a code sample. The latter would be better. – David Heffernan Sep 27 '11 at 18:48
3

Making your function inline avoids this multiple definition problem.

Try,

inline void sayhi()
{
  cout<<"hi";
}

This link might be helpful to you.

In particular, it references section 7.1.2 of the ISO C++ standard:

An inline function shall be defined in every translation unit in which it is used and shall have exactly the same definition in every case (3.2).

which is why the one-definition-rule is circumvented.

Tom
  • 5,219
  • 2
  • 29
  • 45