Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set up CMake to generate header-only projects?

Tags:

c++

c

build

cmake

I want to set up header-only C++ (or C) library projects, but can't find a clean way.

After some searches I've found that you can't set up a normal library using add_library to do this because it requires a compilable source file. A way to do this would be to use add_custom_target instead, this way:

# Get all headers (using search instead of explicit filenames for the example) file( GLOB_RECURSE XSD_HEADERS      *.hxx ) add_custom_target( libsxsd SOURCES ${XSD_HEADERS} ) 

But that doesn't seem to work completely here as I can't see the sources in the project generated in VS2010. I don't know if it's a bug or if I'm doing it wrong or if there is a preferred way to do this.

like image 679
Klaim Avatar asked May 10 '11 22:05

Klaim


People also ask

How do I create a header-only library in CMake?

Creating a Header-Only CMake Target By specifying INTERFACE as the second parameter to add_library , we are no longer allowed to provide source files since the library is not meant to generate any build output.

How do I add a header in CMake?

To include headers in CMake targets, use the command target_include_directories(...) . Depending on the purpose of the included directories, you will need to define the scope specifier – either PUBLIC , PRIVATE or INTERFACE .

How do header-only libraries work?

In the context of the C or C++ programming languages, a library is called header-only if the full definitions of all macros, functions and classes comprising the library are visible to the compiler in a header file form.

What is an interface library CMake?

Interface Libraries Creates an Interface Library. An INTERFACE library target does not compile sources and does not produce a library artifact on disk. However, it may have properties set on it and it may be installed and exported.


1 Answers

Update: CMake will soon include a library target called INTERFACE that is ideal for header-only projects. This feature is currently in the master branch. Reference.

Using the command add_custom_target as you propose works for me (VS2010). The files are neatly listed within my project but it has the drawback that you can't define any "Additional Include Directories" with a custom target. Instead, I now use the following:

add_library(HEADER_ONLY_TARGET STATIC test1.hpp test2.hpp) set_target_properties(HEADER_ONLY_TARGET PROPERTIES LINKER_LANGUAGE CXX) 

This sets up your header-only project as a dummy archive target. Don't worry, no actual binaries will be generated if you should try and build it (at least not in VS2010 and Xcode 4). The command set_target_properties is there because CMake will otherwise complain that it cannot infer the target language from .hpp files only.

like image 94
Frederik Aalund Avatar answered Sep 23 '22 03:09

Frederik Aalund