Home > other >  Pass variable using cmake and print it in C program
Pass variable using cmake and print it in C program

Time:04-03

I'm trying to get a value provided to cmake invocation through to C code so it can be printed. It should be passed like this cmake -DSTR="some text" .. and then in main.c I would do something like puts(STR) to get it printed.

This is what I have so far in CMakeLists.txt, but it does not work:

project(proj)
cmake_minimum_required(VERSION 3.0)

add_definitions(-DSTR)
add_executable(main main.c)

CodePudding user response:

If you want to use puts(STR), then STR has to have " inside it. You have to pass the value of the variable with embedded quotes. For simple cases:

project(proj)
cmake_minimum_required(VERSION 3.0)
add_definitions( "STR=\"${STR}\"" )
add_executable(main main.c)

CodePudding user response:

You may implement this with configure_file and an auxiliary file. E.g.

// File: support_macros.h.in (auxiliary file)

// This file is generated by CMake. Don't edit it.

#define VAR "@VAR@"
// File: main.c

#include "support_macros.h"
#include <stdio>

int main()
{
    puts(VAR);
    // ...
}
# File: CMakeLists.txt

project(proj)
cmake_minimum_required(VERSION 3.0)

# Not needed
# add_definitions(-DSTR)
add_executable(main main.c)

# -- Generate support_macros.h from support_macros.h.in
set(IN_FILE "${CMAKE_SOURCE_DIR}/support_macros.h.in")
set(GENERATED_FILE_PATH "${CMAKE_BINARY_DIR}/GeneratedFiles")  
set(OUT_FILE "${GENERATED_FILE_PATH}/support_macros.h")
configure_file("${IN_FILE}" "${OUT_FILE}" @ONLY)

# -- Make sure main.c will be able to include support_macros.h
target_include_directories(main PRIVATE "${GENERATED_FILE_PATH}")

Then, call cmake passing a value for VAR:

$ cmake .. -DVAR="some text"

Note: by putting quotes around @VAR@ in support_macros.h.in, your main.c will compile even if you don't pass a value for VAR to cmake.

  • Related