So as I was learning, I was told that it’s bad to define function within header files, as if it’s included in multiple places, it’ll produce multiple copies of that function and later causes error in linker. But later I found out that declaring such function with
inline seems to prevent such issue, as stated in this SO answer, if using
inline, the linker will make sure all functions points to the same address.
inlineis just a hint, and it won’t force compiler to really
inlinewill allow you to just declare functions within header files
Then why people bother to use the method “Declare function in header first, then define it in a seperate
.cpp file”, as such approach will require you to compile each
.cpp and also ensure you provide all functions definition files when compiling the main code (something like
g++ lib1.cpp lib2.cpp main.cpp).
As point 1 stated, even if your function is complicated and the compiler might not be able to optimize and inline it, wouldn’t compiler just treat it as a normal function, and later make sure that linker links all calls to the correct, same address?
static, where each unit will have a copy of that function and will result in duplication of functions in executable, as told in the answer I linked above, it doesn’t seem to be the case for
inline. Which I don’t see any disadvantage now to implement functions in
.cpp file rather than just put it all in header.