Search code examples
c++cmakesfml

How to check for current CMake build type in C++?


A little background: I'm writing a game in SFML and I want certain lines of code to be ommitted in Release build. I want to check during compile time for build type, so that is doesn't impact game's performance.

void Tile::draw(sf::RenderTarget& target, sf::RenderStates states) const {
    states.transform *= getTransform();
    target.draw(m_sprite, states);
    #if(DEBUG)
        target.draw(m_collision_shape, states);
    #endif
}

I'm relatively new to CMake world, so I don't even know if it's possible.

EDIT: It's probably worth mentioning I use ninja as a build system.


Solution

  • That's how you might do it in general (working for any generator):

    add_executable(${PROJECT_NAME} main.cpp)
    target_compile_definitions(${PROJECT_NAME} PRIVATE "DEBUG=$<IF:$<CONFIG:Debug>,1,0>")
    

    If you need it for every target you can use the following in the top CMake file (in case you have multiple with add_subdirectory) and before (it is not required but it is less confusing) you created a target. Also as Alex Reinking rightfully corrected we can use a simpler condition, because $<CONFIG:Debug> already gives 1 or 0.

    So applying everything described above we get something like this:

    add_compile_definitions("DEBUG=$<CONFIG:Debug>")
    add_executable(${PROJECT_NAME} main.cpp)