3

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?

3
  • 1
    You might use extra inner namespace. (still visible though). Commented Dec 2, 2021 at 15:01
  • 3
    From C++20, with modules, you might choose what is exported. Commented Dec 2, 2021 at 15:02
  • It should be mentioned that access modifiers and scope aren't very good code security - you have to assume that a user will use undocumented APIs if they're determined, and communicate as best you can with a clearly named inner namespace. Commented Dec 2, 2021 at 15:11

2 Answers 2

4

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 detail, meaning implementation details, or internal meaning internal to your library.

And as mentioned in comments, C++20 modules changes this situation.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.