C++ vs C – Why Method Definitions Can Be Inside Header Files in C++

cheaders

In C, you cannot have the function definition/implementation inside the header file. However, in C++ you can have a full method implementation inside the header file. Why is the behaviour different?

Best Answer

In C, if you define a function in a header file, then that function will appear in each module that is compiled that includes that header file, and a public symbol will be exported for the function. So if function additup is defined in header.h, and foo.c and bar.c both include header.h, then foo.o and bar.o will both include copies of additup.

When you go to link those two object files together, the linker will see that the symbol additup is defined more than once, and won't allow it.

If you declare the function to be static, then no symbol will be exported. The object files foo.o and bar.o will still both contain separate copies of the code for the function, and they will be able to use them, but the linker won't be able to see any copy of the function, so it won't complain. Of course, no other module will be able to see the function, either. And your program will be bloated up with two identical copies of the same function.

If you only declare the function in the header file, but do not define it, and then define it in just one module, then the linker will see one copy of the function, and every module in your program will be able to see it and use it. And your compiled program will contain just one copy of the function.

So, you can have the function definition in the header file in C, it's just bad style, bad form, and an all-around bad idea.

(By "declare", I mean provide a function prototype without a body; by "define" I mean provide the actual code of the function body; this is standard C terminology.)