Last Updated: February 25, 2016
· fish2000
Me at arnhem cropped

Embed a `main()` function in a C++ header file for testing

Sometimes, you want to embed a quick inline test in a C++ file … but what if that file is a header? Compilers won’t let you declare a main() function as static, but you can use this combination of an anonymous namespace and an extern "C" block to achieve the same effect:


/// insert all of your header-file code here ...

namespace {
    extern "C" {
        int main(void) {
            /// ... and here is where your
            ///     inline test code lives.

#endif /* end of include guard: HEADER_FILE */

… it may look weird, but you can then compile the header for testing – just as you would an implementation file that ended in e.g. .cpp – like so, for example:

clang++ -x c++ -std=c++14 -stdlib=libc++
-fstrict-aliasing -Wall -O3 -mtune=native

… Embedding a test main() in this fashion lets you fire off a first-line-of-defense sanity check easily from contemporary editor extensions too, e.g. TextMate bundle commands, Sublime Text build systems, and the like.

Say Thanks