Multiple targets in one CMake project

In my project, I have a makefile that looks like this:

CXX = clang++
CFLAGS = -std=c++11 
COMMON_SOURCES = file1.cpp file2.cpp
TARGET_SOURCES = main.cpp
TEST_SOURCES = run_tests.cpp test_file1.cpp test_file2.cpp
COMMON_OBJECTS = $(COMMON_SOURCES:.c=.o)
TARGET_OBJECTS = $(TARGET_SOURCES:.c=.o)
TEST_OBJECTS = $(TEST_SOURCES:.c=.o)
EXECUTABLE = build/application
TEST_EXECUTABLE = build/tests
.PHONY: all target tests
all: target tests
target: $(EXECUTABLE)
tests: $(TEST_EXECUTABLE)
clean:
    rm build/tests & rm build/application &
$(EXECUTABLE): $(COMMON_OBJECTS) $(TARGET_OBJECTS)
    $(CXX) $(CFLAGS) $(LDFLAGS) $^ -o $@
$(TEST_EXECUTABLE): $(COMMON_OBJECTS) $(TEST_OBJECTS)
    $(CXX) $(CFLAGS) $(LDFLAGS) $^ -o $@
.c.o:
    $(CXX) $(CFLAGS) $< -o $@

      

This allows me to run make tests

or make target

and it will build the corresponding executable.

How can I customize the CMakeLists file to get the same usable build system?

+3


source to share


2 answers


Except for using clang ++, I think if you put the following in your CMakeLists.txt file and then run your cmake config step in your build directory (i.e. mkdir build; cd build; cmake ..

) you should have what you are asking for.



project(myproject)

# I am not sure how you get cmake to use clang++ over g++
# CXX = clang++

add_definitions(-std=c++11)
set(COMMON_SOURCES file1.cpp file2.cpp)
set(TARGET_SOURCES main.cpp)
set(TEST_SOURCES  run_tests.cpp test_file1.cpp test_file2.cpp)
add_executable(application ${COMMON_SOURCES} ${TARGET_SOURCES})
add_executable(tests ${COMMON_SOURCES} ${TEST_SOURCES})

      

+3


source


Each add_custom_target()

(and some other commands like add_executable

) actually add a target to make.

add_custom_target(tests) # Note: without 'ALL'
add_executable(test_executable ...) # Note: without 'ALL'
add_dependencies(tests test_executable)

      



So, it test_executable

will be built on make tests

, but not in the case of a simple one make

.

+1


source







All Articles