Many C++ projects (e.g. many Boost libraries) are “header-only linked”.
Is this possible also in plain C? How to put the source code into headers? Are there any sites about it?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Executive summary: You can, but you shouldn’t.
C and C++ code is preprocessed before it’s compiled: all headers are “pasted” into the source files that include them, recursively. If you define a function in a header and it is included by two C files, you will end up with two copies in each object file (One Definition Rule violation).
You can create “header-only” C libraries if all your functions are marked as
static, that is, not visible outside the translation unit. But it also means you will get a copy of all the static functions in each translation unit that includes the header file.It is a bit different in C++: inline functions are not
static, symbols emitted by the compiler are still visible by the linker, but the linker can discard duplicates, rather than giving up (“weak” symbols).It’s not idiomatic to write C code in the headers, unless it’s based on macros (e.g.
queue(3)). In C++, the main reason to keep code in the headers are templates, which may result in code instantiation for different template parameters, which is not applicable to C.