简体   繁体   English

CMake:如何为测试子目录项目重用目标文件?

[英]CMake: How to reuse an object files for the tests subdirectory project?

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. 我想重用为项目二进制文件编译的class1.o。 Default CMake behavior compiled it twice for test too. 默认的CMake行为也对其进行了两次编译以进行测试。 I try to use OBJECT library but it puts all objects in this library variable. 我尝试使用OBJECT库,但是它将所有对象放入此库变量中。 Then compiler print 然后编译器打印

main.cpp:(.text.startup+0x0): multiple definition of `main' main.cpp :(。text.startup + 0x0):`main'的多个定义

It means that 2 different main.o in one target. 这意味着在一个目标中有2个不同的main.o。 And all other *.o files from main project compilation are. 其他来自主项目编译的* .o文件都是。

How to exlude unneeded *.o files? 如何排除不需要的* .o文件?

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). 您也可以将其保存在单个目录中,但是在构建对象库时仍然需要排除main.cpp,因为否则,在构建测试时,确实会有main多个定义(在main.cpp和测试主体)。

If you are listing the files explicitly (which is highly recommended for CMake ), you can simply omit the main.cpp from the list. 如果要明确列出文件( 强烈建议CMake使用 ),则只需从列表中省略main.cpp即可。 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? 如果使用globbing列出文件,则可以按以下说明从列表中删除文件: 如何从cmake`file(GLOB ...)`模式中排除单个文件?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM