Cmake多库场景

时间:2011-10-05 14:06:47

标签: c++ c cmake

我们想组织一个这样的C++项目:

project/
    lib1/       (first library)
        CMakeList.txt
        src/
            lib1.c
            foo1.h
        build/
        test/       (tests)
            CMakeList.txt
            test1.c
            test2.c
    lib2/       (second library)
        CMakeList.txt
        src/
            CMakeList.txt
            os/              (OS dependent code)
                CMakeList.txt
                win32/
                    xxx.c    (win32 implementation)
                linux/
                    xxx.c    (linux implementation)
            lib2.c
            foo2.h
        build/
    include/    (shared/public headers)
        lib1/
            lib.h    (shared library header included from apps)
        lib2/
            lib.h    (shared library header -"-)

请在CMakeLists.txt使用lib2时使用link1时如何写lib2 CMakeList.txt应该是可移植的(至少是Win32,Linux ......)?

更正:如果某些{{1}}个文件不在他们的位置,请假设如此。我可能忘记了。

1 个答案:

答案 0 :(得分:2)

整个理念是从整个项目的中心CMakeLists.txt开始。在这个级别,所有目标(libs,可执行文件)都将被聚合,因此例如从lib1到lib2的链接没有问题。如果lib2将链接到lib1,则需要首先构建lib1。

平台特定的源文件应该有条件地设置为某个变量。 (如果需要在子目录中设置变量并在上面的目录中使用它,则必须使用CACHE FORCE等将其设置为缓存 - 请参阅set的手册)

这就是你如何正确地完成源代码构建 - 正如CMake所希望的那样:

cd project-build
cmake ../project

每个库具有单独的构建目录并不是非常CMake'ish(如果我可以这样说)并且可能需要 一些黑客。

project-build/
project/
    CMakeLists.txt (whole project CMakeLists.txt)
    [
        project(MyAwesomeProject)

        include_directories(include) # allow lib1 and lib2 to include lib1/lib.h and lib2/lib.h
        add_subdirectory(lib1) # this adds target lib1
        add_subdirectory(lib2) # this adds target lib2

    ]

    lib1/       (first library)
        CMakeList.txt
        [
            add_library(lib1...)
            add_subdirectory(test)
        ]
        src/
            lib1.c
            foo1.h
        test/       (tests)
            CMakeList.txt
            test1.c
            test2.c
    lib2/       (second library)
        CMakeList.txt
        [
            add_subdirectory(src)
        ]
        src/
            CMakeList.txt
            [
                if(WIN32)
                    set(lib2_os_sources os/win32/xxx.c)
                elsif(LINUX)
                    set(lib2_os_sources os/linux/xxx.c)
                else()
                    message(FATAL_ERROR "Unsupported OS")
                endif()
                add_library(lib2 SHARED lib2.c ${lib2_os_sources})
            ]
            os/              (OS dependent code)
                win32/
                    xxx.c    (win32 implementation)
                linux/
                    xxx.c    (linux implementation)
            lib2.c
            foo2.h
    include/    (shared/public headers)
        lib1/
            lib.h    (shared library header included from apps)
        lib2/
            lib.h    (shared library header -"-)