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:
#ifndef HEADER_FILE
#define HEADER_FILE
/// 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
./headerfile.hh
… 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.
Written by Alexander Böhn
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Tdd
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#