[CMake] Excluding definitions for source files

Michael Hertling mhertling at online.de
Thu May 19 04:01:00 EDT 2011


On 05/19/2011 08:18 AM, Robert Bielik wrote:
> Robert Bielik skrev 2011-05-19 07:57:
>>> I have a problem where I need to be able to select Unicode build or not, but at the same time 3 files of my project MUST NOT have
>>> Unicode enabled. Is there a way to remove compile definitions for certain source files ?
>>
>> Oh, and I cannot extract those 3 files into a separate static library as my project _is_ a static library that should have no extra
>> dependencies as viewed from including apps.
> 
> Ok, I did it by set_source_files_properties (compile_definitions) on all source files BUT the 3 I wanted in non-unicode always. Works fine,
> but it would be great with a remove_compile_definitions for set_source_files_properties ? :)
> 
> Regards,
> /Rob

You might add "-UUNICODE" or the like to the affected files'
COMPILE_FLAGS source property; look at this CMakeLists.txt:

CMAKE_MINIMUM_REQUIRED(VERSION 2.8 FATAL_ERROR)
PROJECT(UNDEF C)
SET(CMAKE_VERBOSE_MAKEFILE ON)
FILE(WRITE ${CMAKE_BINARY_DIR}/f.c
"#ifdef UNICODE
#error \"No UNICODE, please!\"
#endif
void f(void){}
")
SET(UNICODE "UNICODE" CACHE STRING "")
SET_SOURCE_FILES_PROPERTIES(${CMAKE_BINARY_DIR}/f.c
    PROPERTIES COMPILE_FLAGS -U${UNICODE})
ADD_DEFINITIONS(-DUNICODE)
ADD_LIBRARY(f STATIC f.c)
SET_TARGET_PROPERTIES(f PROPERTIES COMPILE_DEFINITIONS UNICODE)

The source file is compiled with two -DUNICODE definitions - due to
ADD_DEFINITIONS() and the COMPILE_DEFINITIONS target property - but
its compilation succeeds in spite of that because of the -UUNICODE
undefinition brought in by the file's COMPILE_FLAGS source property.
When reconfiguring with -DUNICODE=XYZ, e.g., you will probably see
the compilation fail.

However, this approach relies on:

1. The source file properties are placed at last on the command line.
   AFAIK, that's not explicitly assured, but reasonable since the
   source file properties are usually the most specific ones.
2. The last -D/-U switch for a preprocessor definition on the
   compiler's command line is the one being in effect. At least,
   GCC assures this: "-D and -U options are processed in the order
   they are given on the command line." and "-U name<\n> Cancel any
   previous definition of name,...".

'hope that helps.

Regards,

Michael


More information about the CMake mailing list