在cmake中将C ++ exe链接到C lib

时间:2017-07-20 17:04:40

标签: cmake linker

我以为我很了解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);

mytest.cpp:

#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

如果我在C ++中编译{​​{1}},那么它链接正常,但不在C中。这对我来说是一个问题,因为我在C中有一个庞大的库,我正在尝试使用boost_test_framework(在C ++中)加载这个lib并测试它。

1 个答案:

答案 0 :(得分:0)

解决方案:

我需要像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);
}