CMake: Definir variables para usarlas en el código
En CMake la definición de variables auxiliares para después utilizarlas en el código es muy sencilla. En esta entrada os dejo una pequeña guía de como definir vuestras varibles, cambiar el valor de las mismas y usarlas dentro del código.
En primer lugar debemos crear un fichero donde vamos a definir las variables estas variables. Este fichero debe tener una extensión .h.cmake para que a la hora de procesarlo con un comando especial de CMake se genere el correspondiente fichero con extensión .h que será el que usemos en nuestros ficheros de código fuente. Vamos a llamar a este fichero libreria.h.cmake, y vamos a definir nuestra primera variable que se llamará PRINT_TIMES
#cmakedefine PRINT_TIMES
Después en el CMakeLists.txt principal del proyecto tenemos que definir el estado inicial de la variable mediante el comando OPTION.
OPTION(PRINT_TIMES "Set to ON to print times of some processes" OFF)
Y en el CMakeLists.txt del directorio donde se encuentre el fichero libreria.h.cmake (en mi caso dentro de una carpeta llamada src) tendremos que colocar las siguientes líneas para que se procese adecuadamente dicho fichero
CONFIGURE_FILE("libreria.h.cmake" "${CMAKE_CURRENT_BINARY_DIR}/libreria.h" <img src='http://plagatux.es/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
Hecho esto, una vez que configuramos el proyecto de forma normal, por defecto nuestra variable toma el valor OFF, por lo que el fichero libreria.h que se genera contendrá la siguiente línea
/* #undef PRINT_TIMES */
Y cuando queremos activar dicha variable tenemos que hacerlo mediante la opción -D del programa cmake (cmake -D PRINT_TIMES=ON ../), de forma que el fichero resultante contendrá la siguiente línea:
#define PRINT_TIMES
Por lo tanto, después podemos usar la siguiente macro dentro de nuestros programas para que solo se ejecute el código correspondiente cuando la variable especificada esté activa
#ifdef PRINT_TIMES /* block of code */ #endif
Si en vez de definir la variable o no hacerlo queremos que la variable esté definida siempre y tome valores de 1 o 0 según la activemos o no, en vez de usar el comando #cmakedefine usaremos #cmakedefine01.
The definition of auxiliary variables in CMake for their later use in the code is very easy. In this post I show you a little guide about how to define these variables, change their values and use them inside the code.
In first place, we have to create a file where to define these variables. This file must have an extension “h.cmake” in order to CMake be able to process it and to generates the final file with extension “.h” which we’ll use in the source code. In this example the file is called “library.h.cmake” and we define inside this the variable PRINT_TIMES.
#cmakedefine PRINT_TIMES
In the CMakeLists.txt file stored in the root of the project folder we have to define the initial value of the variable with the command OPTION.
OPTION(PRINT_TIMES "Set to ON to print times of some processes" OFF)
Then, in the CMakeLists.txt of the source path (where the file “library.h.cmake” resides) we have to add the following lines to process adequately the file
CONFIGURE_FILE("library.h.cmake" "${CMAKE_CURRENT_BINARY_DIR}/library.h" <img src='http://plagatux.es/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
Done these steps, once we configure the project in the default way, our variable will take the value OFF, so the generated file library.h will contain the following line
/* #undef PRINT_TIMES */
If we want to enable this variable we have to run cmake with the option -D PRINT_TIMES=ON. The generated file will contain in this case the following line:
#define PRINT_TIMES
We can use the defined variable in our code in this way
#ifdef PRINT_TIMES /* block of code */ #endif
If Instead of define or not a variable, we want to assign different values (1 or 0) according to its state we will use the command #cmakedefine01.
loading...




loading...
Hola,
felicidades por el articulo. No se si es el sentido que le querias dar pero cuando usas cmakedefine es para cuando quieres poner FLAGS para despues usar con el ifdef
Si en cambio usas un define, puedes usar las variables con un valor, tipo
#define MAX_FILES 100
Con lo que podemos poner variables dentro de nuestro programa. Para ello usarmos en el fichero de configuracion la declaracion de macro asi
#define MAX_FILES @MAX_FILES_values@
Despues, en nuestro fichero CMakeFiles.txt le seteamos el valor con
#SET(MAX_FILES_values 100)
aunque le podemos cambiar el valor sobre linea de comandos tal como ya has explicado. Solo nos queda ejecutar cmake y se hace la magia
Ademas el fichero de configuracion no tiene por que terminar obligatoriamente con .cmake. Podemos usar cualquier terminacion.
loading...
Hola! llevas razón eso no lo he dejado claro del todo, aunque en el último bloque de código veras que uso la macro IFDEF. Respecto a lo último que comentas de la terminación .cmake también llevas razón pero es una costumbre que he cogido para saber que ficheros pertenecen a la configuración del proyecto en cmake
.
Saludos!