66

I'd like to store the version number of my library in just one place. So I have defined such a variable in the CMake-file:

    SET(LIBINTERFACE_VERSION 1 CACHE INTEGER "Version of libInterface")

With this definition I can generate a version.rc file according to Microsoft's definition, which I compile into the library and afterwards shows up correctly in the properties window of my dll-file.

Now I'd like to use this CMake variable in my c++ source code too, but I actually don't get to a working solution. I've tried different things like this:

    #ifndef VERSION_LIBINTERFACE
    #  define VERSION_LIBINTERFACE @LIBINTERFACE_VERSION@
    #endif

or this:

    unsigned int getLibInterfaceVersion()
    {
        return @LIBINTERFACE_VERSION@;
    }

But the compiler won't accept anything. Since my researches in the CMake-Documentation didn't get any results, I hope that someone could give me the essential advice.

Thanks in advance.

2
  • You need to pass this variable value to compiler as precompiler constant. Exact syntax depends on compiler used. Commented Oct 26, 2011 at 9:10
  • I'm using the Visual Studio 2010 Compiler. So I can use it like the constants listed in msdn.microsoft.com/en-us/library/b0084kay(v=vs.80).aspx? Can you give me an example? Commented Oct 26, 2011 at 9:27

1 Answer 1

100

The easiest way to do this, is to pass the LIBINTERFACE_VERSION as a definition with add_definition:

add_definitions( -DVERSION_LIBINTERFACE=${LIBINTERFACE_VERSION} )

However, you can also create a "header-file template" and use configure_file. This way, CMake will replace your @LIBINTERFACE_VERSION@. This is also a little more extensible because you can easily add extra defines or variables here...

E.g. create a file "version_config.h.in", looking like this:

#ifndef VERSION_CONFIG_H
#define VERSION_CONFIG_H

// define your version_libinterface
#define VERSION_LIBINTERFACE @LIBINTERFACE_VERSION@

// alternatively you could add your global method getLibInterfaceVersion here
unsigned int getLibInterfaceVersion()
{
    return @LIBINTERFACE_VERSION@;
}

#endif // VERSION_CONFIG_H

Then add a configure_file line to your cmakelists.txt:

configure_file( version_config.h.in ${CMAKE_BINARY_DIR}/generated/version_config.h )
include_directories( ${CMAKE_BINARY_DIR}/generated/ ) # Make sure it can be included...

And of course, make sure the correct version_config.h is included in your source-files.

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

3 Comments

add_definitions is probably easier
@frankliuao. Agreed, that's why it is the first sentence of my answer.
This is then passed to all targets, better to use target_compile_definitions

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.