I am writing a header-only template library in C . I want to able to write some helper functions inside that header file that will not be visible from a cpp file that includes this header library. Any tips on how to do this?
I know static keyword can be used in cpp files to limit visibility to that one translation unit. Is there something similar for header files?
CodePudding user response:
There isn't really a way.
The convention is to use a namespace for definitions that are not meant to be public. Typical names for this namespace are details
, meaning implementation details, or internal
meaning internal to your library.
And as mentioned in comments, C 20 modules changes this situation.
CodePudding user response:
The easy answer is no.
Headers do not exist to the linker, so all functions in the headers are actually in the module that included them. Technically static (or anonymous namespace) functions in a header, are static to the module that included them. This might work, but you will end up with multiple functions, and bloated code-sizes.
Due to this you should always inline functions in header files, or use something that implies inline - like constexpr; If possible...
Function in headers usually rely on either being inline, or templated. A templated function is "weak", meaning the linker assumes that they are all the same, and just uses a random one, and discards the others.