代码之家  ›  专栏  ›  技术社区  ›  Stewart

将C++exe链接到cmake中的C库

  •  0
  • Stewart  · 技术社区  · 7 年前

    我原以为我很了解cmake,直到我遇到了这个我就是想不出来的问题。我用C语言构建了一个静态库,我正试图用C++对其进行单元测试,但我似乎无法链接到该库中的任何静态函数,我也不知道为什么。我在下面的骨架项目中再现了这个问题:

    CMakeLists.txt:

    cmake_minimum_required(VERSION 3.6) 
    project(myproj) 
    
    add_library(mylib STATIC mylib.c) 
    
    find_package(Boost 1.64.0 COMPONENTS unit_test_framework) 
    
    add_executable(mytestapp mytest.cpp) 
    target_include_directories(mytestapp PRIVATE .) 
    target_link_libraries(mytestapp mylib) 
    
    enable_testing() 
    add_test( mytest mytestapp)
    

    mylib.c:

    int add(int a, int b)
    {
        return a + b;
    }
    

    mylib.h

    int add(int a, int b);
    

    #define BOOST_TEST_MODULE mylib_test
    #include <boost/test/included/unit_test.hpp>
    #include "mylib.h"
    
    BOOST_AUTO_TEST_CASE(mylib_test)
    {
        BOOST_TEST( add(2,2) == 4);
    }
    

    那么我的输出是:

    $ make
    Scanning dependencies of target mylib
    [ 25%] Building C object CMakeFiles/mylib.dir/mylib.c.o
    [ 50%] Linking C static library libmylib.a
    [ 50%] Built target mylib
    Scanning dependencies of target mytestapp
    [ 75%] Building CXX object CMakeFiles/mytestapp.dir/mytest.cpp.o
    [100%] Linking CXX executable mytestapp
    CMakeFiles/mytestapp.dir/mytest.cpp.o: In function `mylib_test::test_method()':
    mytest.cpp:(.text+0x1e411): undefined reference to `add(int, int)'
    collect2: error: ld returned 1 exit status
    make[2]: *** [CMakeFiles/mytestapp.dir/build.make:96: mytestapp] Error 1
    make[1]: *** [CMakeFiles/Makefile2:105: CMakeFiles/mytestapp.dir/all] Error 2
    make: *** [Makefile:95: all] Error 2
    

    如果我编译 mylib

    1 回复  |  直到 7 年前
        1
  •  1
  •   Stewart    7 年前

    解决方案:

    我需要用 extern "C"

    #define BOOST_TEST_MODULE mylib_test
    #include <boost/test/included/unit_test.hpp>
    
    extern "C" {
      #include "mylib.h"
    }
    
    BOOST_AUTO_TEST_CASE(mylib_test)
    {
        BOOST_TEST( add(2,2) == 4);
    }