1

My project is something like this:

project
├── test
│   ├── CMakeLists.txt
│   ├── main.cpp
│   └── test_class1.cpp
├── CMakeLists.txt
├── main.cpp
├── ...
├── class1.h
└── class1.cpp

I want to reuse class1.o which was compiled for project binary. Default CMake behavior compiled it twice for test too. I try to use OBJECT library but it puts all objects in this library variable. Then compiler print

main.cpp:(.text.startup+0x0): multiple definition of `main'

It means that 2 different main.o in one target. And all other *.o files from main project compilation are.

How to exlude unneeded *.o files?

Kroll
  • 649
  • 2
  • 6
  • 17

1 Answers1

5

What I normally do is that I separate the application logic into a static library (subdirectory), which is then used by both the main application and the tests.

You could keep it in a single dir as well, but then you still need to exclude the main.cpp when building the object library, because otherwise you will indeed have multiple definitions of main when building tests (as defined in both main.cpp and the test main).

If you are listing the files explicitly (which is highly recommended for CMake), you can simply omit the main.cpp from the list. If you use globbing to list the files, you can remove the file from the list as described here: How do I exclude a single file from a cmake `file(GLOB ... )` pattern?

Community
  • 1
  • 1
EmDroid
  • 5,918
  • 18
  • 18
  • This. Compile your classes into libraries if you want to easily reuse them throughout the project. – Nicolas Holthaus Feb 01 '17 at 14:01
  • I decide to use "list operations". First I added all main project sources to SRC_LIST: `aux_source_directory(${PROJECT_SOURCE_DIR} SRC_LIST)` Then I exclude some sources to object library for make them shared: `set(SHARED_SRC ${PROJECT_SOURCE_DIR}/event_bus.cpp ${PROJECT_SOURCE_DIR}/event.cpp) list(REMOVE_ITEM SRC_LIST ${SHARED_SRC}) add_library(TESTING_OBJECTS OBJECT ${SHARED_SRC})` Now I can use this precompiled objects both in main project and tests like this: `set(SRC_LIST ${SRC_LIST} $)` – Kroll Feb 02 '17 at 06:41