Thursday, April 14, 2022

[SOLVED] Pass variable using cmake and print it in C program

Issue

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)

Solution

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.



Answered By - paolo
Answer Checked By - David Goodson (WPSolving Volunteer)