2013-02-17 35 views
1

我只在相應的源文件被特定cmake目標使用時才啓用C宏。假設我有以下設置:根據cmake目標啓用宏

tests/test.cpp 
src/code.cpp 
include/code.hpp 
CMakeList.txt 

code.hpp

class MyClass 
{ 
public: 
    void normal_stuff(); 
#ifdef TEST 
    int debug; 
    void _dangerous_function() 
    { 
     debug++; 
    } 
#endif 
} 

code.cpp

#include "code.hpp" 

MyClass::normal_stuff() 
{ 
    // boring code 
} 

TEST.CPP

#include "code.hpp" 

void some_test() 
{ 
    MyClass foo; 
    foo._dangerous_function(); 
} 

CMakeList.txt

project(foo) 
include_directories(include) 
file(GLOB_RECURSE foo_source src/*.cpp) 
file(GLOB_RECURSE test_source test/*.cpp) 
add_executeable(foo ${foo_source}) 
add_executeable(test ${test_source} ${foo_source}) 

我想設置測試僅當code.cpp是爲測試目標而不是爲foo目標而構建的。當然,之前我有code.hpp,但隨後code.cpp將有MyClass的比TEST.CPP有不同的看法,我可以只寫在TEST.CPP「的#define TEST」。

有沒有人有一個想法我可以做到這一點?我知道,我不應該這樣做,但我想知道,如果我能得到它運行。

回答

3

你可以設定一個目標特定的屬性添加這樣的定義:

set_target_properties(test PROPERTIES COMPILE_DEFINITIONS "TEST") 

更多herehere

+0

非常感謝您!奇蹟般有效。 :-) – themarex 2013-02-17 09:32:08