在gtest中,如何添加库文件到可执行的测试文件

in gtest, how to add lib file to executable test file

本文关键字:文件 可执行 测试 添加 gtest 何添加      更新时间:2023-10-16

我总是得到undefined reference to m(),这是我的代码:

ex.c

#include "stdio.h"
void m() {
}

ex.h

void m();

ex_test.cpp

#include "gtest/gtest.h"
#include "ex.h"
TEST(m, 1) {
    m();
}

CMakeLists.txt

cmake_minimum_required(VERSION 3.1)
project(try)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
set(src ex.c)
add_executable(try ${src})
add_subdirectory(gtest)
include_directories(${gtest_SOURCE_DIR} ${gtest_SOURCE_DIR}/include)
add_executable(ex_test ex_test.cpp ex.c)
target_link_libraries(ex_test gtest gtest_main)

这是我的输出(对不起,sofraise "most code"错误时,我复制它

ex.c编译为C。ex_test.cpp编译为c++,但指的是m()来自ex.c,所以在ex_test.cpp中您需要通知编译器ex.h中的声明具有C链接(因此没有名称混淆)。

替换:

#include "ex.h"

:

extern "C" {
#include "ex.h"
}

您的问题标题正好指出了问题所在:您应该将ex的库添加到ex_test所需的库文件中。

编译ex.c,然后将编译结果文件ex.a附加到ex_test所需的库文件中。你可以这样做,write CMakeLists.txt文件如下:

add_library(ex ex.c)
target_link_libraries(ex_test ex gtest gtest_main)
相关文章: