开发者

inclusion of header files

开发者 https://www.devze.com 2023-04-08 11:54 出处:网络
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 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??


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号