How to use target_compile_definitions ?

Here is my naive attempt at using target_compile_definitions:

cmake_minimum_required(VERSION 3.12.1 FATAL_ERROR)
project(p)

add_library(foo foo.cpp)

set(defs "-D_GNU_SOURCE -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS")
target_compile_definitions(foo PRIVATE ${defs})

This gives:

/usr/bin/c++ -D_GNU_SOURCE -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS="64 -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS" 

How should I use this function instead in this example ?

Thanks much

target_compile_definitions expects a list, not a string. Moreover, the format expected, as specified in the documentation, is:

Definitions are specified using the syntax VAR or VAR=value

So:

set(defs _GNU_SOURCE _LARGEFILE_SOURCE _FILE_OFFSET_BITS=64 __STDC_CONSTANT_MACROS __STDC_FORMAT_MACROS __STDC_LIMIT_MACROS)
target_compile_definitions(foo PRIVATE ${defs})

Very nice ! Thanks for the quick answer. Now would you have a suggestion to refactor this:

find_package(LLVM REQUIRED)
target_compile_definitions(foo PRIVATE ${LLVM_DEFINITIONS})

A little correction: target_compile_definitions supports -D flag as part of arguments (I confuse with add_compile_definitions).

Now, I don’t know LLVM package. But if LLVM_DEFINITIONS is specified as a string, I think target_compile_definitions(foo PRIVATE ${LLVM_DEFINITIONS}) is OK.

But, it seems there is a bug in the parsing of the arguments. As you already discovered. If a definition has a value, the rest of the arguments are included as part of the value. So I suggest you to create a bug for that.

And as a workaround, use separate_arguments:

set (CLEAN_DEFS ${LLVM_DEFINITIONS})
separate_arguments(CLEAN_DEFS)
target_compile_definitions(target PRIVATE ${CLEAN_DEFS})

Thanks much !