Can you exclude certain source files from different build configurations?

I’m working on a project that runs on an embedded board with an ARM9 processor. The board was originally running Linux with a 2.6.0 kernel and we recently upgraded to use a 5.1.0 kernel and I’m now trying to sort out the build files. The new kernel came with a toolchain that uses a newer version of the C/C++ compiler and is not compatible with the old kernel but I still have to support the old kernel.
The original project used makefiles, which was reasonably easy to maintain when there was only a need to compile code for the developers machine and a single kernel. However with two different kernels to support, I’ve decided to use CMake in an attempt to make the builds easier to manage. CMake is new to me but I have figured out how to use the CMAKE_TOOLCHAIN_FILE to create build configurations for different cross compilers.

The original version of the code used a cJSON module (a single cJSON.h and single cJSON.c file) and, for reasons unknown, the developer decided to include the source file in the project and compile it into one of the projects libraries, rather than create a separate library. When we moved to the new kernel, it came with a libcjson shared library and an include file in the toolchain include path.

What that means is that when I build the code for the 2.6.0 kernel, I need to point to the include file in my project’s source directory and compile the cJSON.c file into the project library file but when building for the 5.1.0 file, I need to exclude both these files from the build and use cJSON.h from the toolchain include file and link against the toolchain’s

I have compiler macros setup to tell which version of the kernel I’m building for (-DK260 or -DK510) and can do some preprocessor code to point to different include files (“cJSON.h” vs <cjson/cJSON.h>) but is there a way I tell CMake to exclude the cJSON.c from the K260 compile and include it in the K510 compile? Can I do this through the CMAKE_TOOLCHAIN_FILE? Any other way?


How do you set up the appropriate compiler macros?
If the logic of definition of the compiler macro is done in CMake you can use the same logic
to add (or not add) source to a particular target.

Using guarded by appropriate condition seems a good use case.

You should be able to define a CMake variable whose value is readable in your CMakeLists.txt so that
depending on the value you can add appropriate source file.

I create the compiler macros with the add_definitions command.