CMake: Is it possible to build an executable from only static libraries and no source?

前端 未结 2 1331
粉色の甜心
粉色の甜心 2020-12-10 13:52

I would like to build an executable from static libraries (i. e. .a-files) only. This is possible, because the main() function is contained in one of these libr

2条回答
  •  隐瞒了意图╮
    2020-12-10 14:16

    There are mainly two reasons why a source file is enforced by CMake:

    1. To determine the LINKER_LANGUAGE from the file ending(s)
    2. Not all compilers do support an object/library only link step (for details see below)

    And if you move the main() function to library please keep the following in mind: Why does the order in which libraries are linked sometimes cause errors in GCC?

    So if you build the libraries with CMake in the same project, I would recommend to change your libraries (at least the one containing your main() function) to an object library:

    cmake_minimum_required(VERSION 2.8.8)
    
    project(NoSourceForExe)
    
    file(WRITE main.cc "int main() { return 0; }")
    
    add_library(MyLibrary OBJECT main.cc)
    add_executable(MyExecutable $)
    

    The add_library() documentation lists a warning 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 $.

    But those are rare and listed in Tests/ObjectLibrary/CMakeLists.txt:

    # VS 6 and 7 generators do not add objects as sources so we need a
    # dummy object to convince the IDE to build the targets below.
    ...
    # Xcode does not seem to support targets without sources.
    

    Not knowing which host OS(s) you are targeting, you may just give it a try.

    References

    • CMake Object Lib containing main
    • CMake/Tutorials/Object Library

提交回复
热议问题