Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a C #define for a certain target using CMake?

Tags:

cmake

I feel a little stupid right now. After recently converting a few smaller projects to use CMake, I decided to also get rid of a few "Platform_Config.h" files. These files contain a few preprocessing directives like #define USE_NEW_CACHE and control compilation.

How would I 'convert' these defines to be controlled with CMake? Ideally by using these "cache" variables the user can easily edit.

like image 770
Marcus Riemer Avatar asked Mar 18 '11 12:03

Marcus Riemer


People also ask

What is C used to create?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is needed to write a basic C?

Aside from a compiler, the only other software requirement is a text editor for writing and saving your C code.


2 Answers

There are two options. You can use the add_definitions method to pass defines as compiler flags: E.g. somewhere in your projects cmakelists.txt:

add_definitions( -DUSE_NEW_CACHE )

CMake will make sure the -D prefix is converted to the right flag for your compiler (/D for msvc and -D for gcc).

Alternatively, check out configure_file. It is more complex, but may be better suited to your original approach with a Platform_Config file.

You can create an input-file, similar to your original Platform_Config.h and add "#cmakedefine" lines to it.

Let's call in Platform_Config.h.in:

// In Platform_Config.h.in
#cmakedefine USE_NEW_CACHE
// end of Platform_Config.h.in

When then running

configure_file( ${CMAKE_SOURCE_DIR}/Platform_Config.h.in ${CMAKE_BINARY_DIR}/common/Platform_Config.h )

it will generate a new Platform_Config file in your build-dir. Those variables in cmake which are also a cmakedefine will be present in the generated file, the other ones will be commented out or undefed.

Of course, you should make sure the actual, generated file is then correctly found when including it in your source files.

like image 52
André Avatar answered Sep 21 '22 12:09

André


option command might provide what you are looking for.
use it with the COMPILE DEFINITIONS property on the target and i think you are done. To set the property on the target, use the command set target properties

option(DEBUGPRINTS "Prints a lot of debug prints")
target(myProgram ...)
if(DEBUGPRINTS)
set_target_properties(myProgram PROPERTIES COMPILE_DEFINITIONS "DEBUGPRINTS=1")
endif()

edit:

The option i wrote in the example shows up as a checkbox in the CMake GUI.

like image 20
0xbaadf00d Avatar answered Sep 19 '22 12:09

0xbaadf00d