CMake Object包含main [英] CMake Object Lib containing main

查看:2601
本文介绍了CMake Object包含main的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于CMake,如果我们想用相同的主函数创建不同的可执行文件,我们可以创建一个包含main函数的库(它在 main.cpp 中说)通过以下方式将其链接到所有高管:

With CMake if we wanted to create different executables with the same main function we could create a library containing the main function (which is in main.cpp, say) and link it to all execs by:

add_library(main_lib main.cpp)
add_executable(exe1 source1.cpp)
target_link_libraries(exe1 main_lib)

等等。这样,我们必须为每个exec指定至少一个源文件。如果我们没有源文件,只想链接execs与不同的libs?

and so on for other executables. This way, however, we have to specify at least one source file for each exec. What if we have no source files and only want to link execs with different libs?

add_executable(exe1) #(1)
target_link_libraries(exe1 some_lib1 main_lib)


$ b < (1)。有一个对象库,我们可以使用:

Unfortunately, CMake does not allow (1). There is an Object Library that we could use:

add_library(main_lib OBJECT main.cpp) 
add_executable(exe1 $<TARGET_OBJECTS:main_lib>) #(2)
target_link_libraries(exe1 some_lib1)

(2)会产生以下结果:

CMakeFiles/main_obj.dir/test_caffe_main.cpp.o: In function `main':
test_caffe_main.cpp:(.text+0x0): multiple definition of `main'
CMakeFiles/test_caffe_main.testbin.lib.dir/test_caffe_main.cpp.o:test_caffe_main.cpp:(.text+0x0): first defined here

如果没有其他源文件,我们如何在不同的可执行文件中重用包含main函数的目标文件?

How can we reuse an object file containing a main function in different executables when there are no other source files?

编辑:
对象库在主函数中工作得很好。原来,我确实包括一个错误的第二个主要。很抱歉发布!

Object Library works very well with main functions. It turned out I did include a second main by a mistake. Sorry for posting it!

推荐答案

使用对象库



看起来像您无意中将库链接到目标:

Using object library

Looks like you unintentionally link library to target:

add_library(with_main OBJECT main.cpp)
add_executable(foo $<TARGET_OBJECTS:with_main>) # Target without any source files

# target_link_libraries(foo with_main) # Not needed here



问题



对于某些生成器,对象库方法可能无效。请参阅文档

Some native build systems may not like targets that have only object files,
so consider adding at least one real source file to any
target that references $<TARGET_OBJECTS:objlib>

* 我在Xcode上有些麻烦,但现在我测试这个例子(由homebrew安装的cmake 3.0.1)

对象(只传递空字符串):

You can do it without objects (just pass empty string):

add_library(with_main main.cpp)
add_executable(foo "")
target_link_libraries(foo with_main)

但在这种情况下,CMake无法确定目标 foo 。通常这通过分析源列表(foo.cpp - > linker CXX,foo.c - > linker C)来完成。现在需要明确设置:

but in this case CMake can't determine the linker for target foo. Usually this done by analizing list of sources (foo.cpp -> linker CXX, foo.c -> linker C). Now you need to set it explicitly:

set_target_properties(foo PROPERTIES LINKER_LANGUAGE CXX)

这篇关于CMake Object包含main的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆