0

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)
  • Does this answer your question? [Define preprocessor macro through CMake?](https://stackoverflow.com/questions/9017573/define-preprocessor-macro-through-cmake) – kaylum Apr 03 '22 at 09:30
  • `it does not work:` is very very vague. What happens exactly? What messages are there? – KamilCuk Apr 03 '22 at 10:44

2 Answers2

1

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.

paolo
  • 2,345
  • 1
  • 3
  • 17
1

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)
KamilCuk
  • 120,984
  • 8
  • 59
  • 111