Buscar..


Introducción

configure_file es una función CMake para copiar un archivo a otra ubicación y modificar su contenido. Esta función es muy útil para generar archivos de configuración con rutas, variables personalizadas, utilizando una plantilla genérica.

Observaciones

Copia un archivo a otra ubicación y modifica su contenido.

configure_file(<input> <output>
           [COPYONLY] [ESCAPE_QUOTES] [@ONLY]
           [NEWLINE_STYLE [UNIX|DOS|WIN32|LF|CRLF] ])

Copia un archivo a archivo y sustituye los valores de las variables a las que se hace referencia en el contenido del archivo. Si es una ruta relativa, se evalúa con respecto al directorio de origen actual. El debe ser un archivo, no un directorio. Si es una ruta relativa, se evalúa con respecto al directorio binario actual. Si nombra un directorio existente, el archivo de entrada se coloca en ese directorio con su nombre original.

Si se modifica el archivo, el sistema de compilación volverá a ejecutar CMake para volver a configurar el archivo y volver a generar el sistema de compilación.

Este comando reemplaza cualquier variable en el archivo de entrada referenciado como $ {VAR} o @ VAR @ con sus valores según lo determinado por CMake. Si una variable no está definida, será reemplazada por nada. Si se especifica COPYONLY, entonces no tendrá lugar la expansión de la variable. Si se especifica ESCAPE_QUOTES, todas las citas sustituidas serán de estilo C con escape. El archivo se configurará con los valores actuales de las variables CMake. Si se especifica @ONLY, solo se reemplazarán las variables de la forma @ VAR @ y se ignorará $ {VAR}. Esto es útil para configurar scripts que usan $ {VAR}.

Las líneas del archivo de entrada con el formato "#cmakedefine VAR ..." se reemplazarán con "#define VAR ..." o / * #undef VAR * / dependiendo de si VAR está configurado en algún valor que no se considere falso constante por el comando if (). (El contenido de "...", si corresponde, se procesa como se indicó anteriormente). Las líneas de archivo de entrada con el formato "# cmakedefine01 VAR" se reemplazarán con "#define VAR 1" o "#define VAR 0" de manera similar.

Con NEWLINE_STYLE se podría ajustar el final de la línea:

'UNIX' or 'LF' for \n, 'DOS', 'WIN32' or 'CRLF' for \r\n.

COPYONLY no debe usarse con NEWLINE_STYLE.

Generar un archivo de configuración de c ++ con CMake

Si tenemos un proyecto c ++ que usa un archivo de configuración config.h con algunas rutas o variables personalizadas, podemos generarlo usando CMake y un archivo genérico config.h.in.

El archivo config.h.in puede formar parte de un repositorio git, mientras que el archivo config.h generado nunca se agregará, ya que se genera desde el entorno actual.

#CMakeLists.txt
CMAKE_MINIMUM_REQUIRED(VERSION 2.8.11)

SET(PROJ_NAME "myproject")
PROJECT(${PROJ_NAME})

SET(${PROJ_NAME}_DATA     ""     CACHE PATH "This directory contains all DATA and RESOURCES")
SET(THIRDPARTIES_PATH    ${CMAKE_CURRENT_SOURCE_DIR}/../thirdparties      CACHE PATH "This directory contains thirdparties")

configure_file ("${CMAKE_CURRENT_SOURCE_DIR}/common/config.h.in"
            "${CMAKE_CURRENT_SOURCE_DIR}/include/config.h" )

Si tenemos una config.h.in como esta:

cmakedefine PATH_DATA "@myproject_DATA@"
cmakedefine THIRDPARTIES_PATH "@THIRDPARTIES_PATH@"

Las CMakeLists anteriores generarán un encabezado de c ++ como este:

#define PATH_DATA "/home/user/projects/myproject/data"
#define THIRDPARTIES_PATH "/home/user/projects/myproject/thirdparties"

Examble basado en la versión de control SDL2

Si tienes un módulo cmake . Se puede crear una carpeta llamada in almacenar todos los archivos de configuración.

Por ejemplo, usted tiene un proyecto llamado FOO , puede crear un archivo FOO_config.h.in como:

//===================================================================================
//  CMake configuration file, based on SDL 2 version header
// ===================================================================================

#pragma once

#include <string>
#include <sstream>

namespace yournamespace
{
  /**
 *  \brief Information the version of FOO_PROJECT in use.
 *
 *  Represents the library's version as three levels: major revision
 *  (increments with massive changes, additions, and enhancements),
 *  minor revision (increments with backwards-compatible changes to the
 *  major revision), and patchlevel (increments with fixes to the minor
 *  revision).
 *
 *  \sa FOO_VERSION
 *  \sa FOO_GetVersion
 */
typedef struct FOO_version
{
    int major;        /**< major version */
    int minor;        /**< minor version */
    int patch;        /**< update version */
} FOO_version;

/* Printable format: "%d.%d.%d", MAJOR, MINOR, PATCHLEVEL
*/
#define FOO_MAJOR_VERSION   0
#define FOO_MINOR_VERSION   1
#define FOO_PATCHLEVEL      0

/**
 *  \brief Macro to determine FOO version program was compiled against.
 *
 *  This macro fills in a FOO_version structure with the version of the
 *  library you compiled against. This is determined by what header the
 *  compiler uses. Note that if you dynamically linked the library, you might
 *  have a slightly newer or older version at runtime. That version can be
 *  determined with GUCpp_GetVersion(), which, unlike GUCpp_VERSION(),
 *  is not a macro.
 *
 *  \param x A pointer to a FOO_version struct to initialize.
 *
 *  \sa FOO_version
 *  \sa FOO_GetVersion
 */
#define FOO_VERSION(x)                          \
{                                   \
    (x)->major = FOO_MAJOR_VERSION;                 \
    (x)->minor = FOO_MINOR_VERSION;                 \
    (x)->patch = FOO_PATCHLEVEL;                    \
}

/**
 *  This macro turns the version numbers into a numeric value:
 *  \verbatim
    (1,2,3) -> (1203)
    \endverbatim
 *
 *  This assumes that there will never be more than 100 patchlevels.
 */
#define FOO_VERSIONNUM(X, Y, Z)                     \
    ((X)*1000 + (Y)*100 + (Z))

/**
 *  This is the version number macro for the current GUCpp version.
 */
#define FOO_COMPILEDVERSION \
    FOO_VERSIONNUM(FOO_MAJOR_VERSION, FOO_MINOR_VERSION, FOO_PATCHLEVEL)

/**
 *  This macro will evaluate to true if compiled with FOO at least X.Y.Z.
 */
#define FOO_VERSION_ATLEAST(X, Y, Z) \
    (FOO_COMPILEDVERSION >= FOO_VERSIONNUM(X, Y, Z))

}

// Paths
#cmakedefine FOO_PATH_MAIN "@FOO_PATH_MAIN@"

Este archivo creará un FOO_config.h en la ruta de instalación, con una variable definida en c FOO_PATH_MAIN desde la variable cmake. Para generarlo, debe incluirlo in archivo en su CMakeLists.txt, como este (establecer rutas y variables):

MESSAGE("Configuring FOO_config.h ...")
configure_file("${CMAKE_CURRENT_SOURCE_DIR}/common/in/FOO_config.h.in"
"${FOO_PATH_INSTALL}/common/include/FOO_config.h" )

Ese archivo contendrá los datos de la plantilla y la variable con su ruta real, por ejemplo:

// Paths
#define FOO_PATH_MAIN "/home/YOUR_USER/Respositories/git/foo_project"


Modified text is an extract of the original Stack Overflow Documentation
Licenciado bajo CC BY-SA 3.0
No afiliado a Stack Overflow