Link error with really simple functions C++ on .h file

后端 未结 4 1063
离开以前
离开以前 2021-01-05 19:09

I\'ve made two functions to \'cast\' a 32/64 bit pointer into a double. The code worked when used alone (Just the .h and a .cpp including it) but when using the .h somewhere

4条回答
  •  清歌不尽
    2021-01-05 19:22

    You get the error because the functions are compiled twice (each time the header is included), and so the linker, which combines all the object files into the final executable, sees multiple definitions of the functions.

    Like Armen wrote, one solution is to make the functions inline. This way the code for the functions is always copied whenever they are used. This is a feasible solution here because the functions are so small that the code won't get very bloated. If you have any larger functions in a header file or you need to organize your code better, you should take the code from the header file and put in in a cpp file (like in sehe's answer).

提交回复
热议问题