Search code examples
c++visual-studio-2015cmakegoogletest

Files exclusion (custom and transient) from build


I have many C++ (Google Test) source files in my Visual Studiosolution and I want to have the possibility to keep only a few for the build (to focus on the problem), but also to come back quick enough (two times by day) to the initial configuration.

We are using, more or less, about three solutions: Visual Studio, CMake and QT (but I could add yet another one). I never used QT, so the other two solutions I see are:

  • Visual Studio: folders are useless, but I can select files and exclude them from build. But these changes are saved in vcproj so I have to pay attention not to save them on the version control, which is annoying.
  • CMake: easy change the CMakeLists.txt (comment lines with the sources folders), but I always have the version control problem ... maybe I can configure the excluded files in a custom (user) file. Advantage: I can generate only what I want, more flexible and not so boring like the previous one.

By example, if I do not want the sources in src_2:

file(GLOB_RECURSE SRC_FILES_1
${SOURCE_BASE_DIR}/src_1/*.cpp
${SOURCE_BASE_DIR}/src_1/*.h
)

file(GLOB_RECURSE SRC_FILES_2
${SOURCE_BASE_DIR}/src_2/*.cpp
${SOURCE_BASE_DIR}/src_2/*.h
)

file(GLOB_RECURSE SRC_FILES_3
${SOURCE_BASE_DIR}/src_3/*.cpp
${SOURCE_BASE_DIR}/src_3/*.h
)

add_executable(${PROJECT_TEST_NAME}
${SRC_FILES_1}
# next line is commented
# ${SRC_FILES_2}
${SRC_FILES_3}
)

Is there another solution or a way to improve one of these proposed here?


Solution

  • You can control this with a cmake variable.

    option(BUILD_TESTS "builds test cpp files" ON)
    

    This adds an option for your cmake file. It defaults in this case to ON you can change that though. Now lets get on:

    if(BUILD_TESTS)
        set(TEST_CPP_FILES test1.cpp test2.cpp)
    endif(BUILD_TESTS)
    
    add_executabe(foo bar.cpp bar1.cpp $(TEST_CPP_FILES))
    

    Here you define a variable with the source file of your tests (or whatever source files you want to build when the BUILD_TESTS is ON. These then get added to the target. If BUILD_TESTS is off this variable will be empty.

    now to change the Value you can run

    cmake <...>  -DBUILD_TESTS=OFF
    

    Or with ON if you want to turn them back on again. You also can keep the change in version control because it will default to ON and you need to explicitly disable it.

    You can also exclude whole subdirectories or targets with this in the if statement if you not just only want to exclude source files.

    EDIT:

    For your example it could look like this:

    if(BUILD_TESTS)
        file(GLOB_RECURSE SRC_FILES_2
        ${SOURCE_BASE_DIR}/src_2/*.cpp
        ${SOURCE_BASE_DIR}/src_2/*.h
        )
    endif(BUILD_TESTS)
    

    SRC_FILES_2 should be empty afterwards.