首页 > 解决方案 > Cmake 对函数 hello() 的未定义引用

问题描述

试图让 cmake 为一个小项目工作,但不断获得对 `hello() 的未定义引用,并检查了其他线程可能有什么问题但无法弄清楚。

目录布局如下:

Source_root
|----CMakeLists.txt
    |----tests
        |----test_files.cpp
        |----test_main.cpp
        |----CMakeLists.txt
    |----source
        |----source_test.c
        |----source_test.h

source_root cmake 文件:

cmake_minimum_required(VERSION 3.14.5)
project(test_CPPUTEST)
set(CMAKE_CXX_STANDARD 14)
SET(UNITNAME CPP_U_TEST)
SET(SWC_PATH ${CMAKE_CURRENT_SOURCE_DIR})
add_subdirectory(source)
add_subdirectory(tests)

测试目录

cmake 文件:

cmake_minimum_required(VERSION 3.14.5)
project(test_CPPUTEST)

# CppUTest
include(FetchContent)
FetchContent_Declare(
        CppUTest
        GIT_REPOSITORY https://github.com/cpputest/cpputest.git
        GIT_TAG        master # or use release tag, eg. v3.8
)
# Set this to ON if you want to have the CppUTests in your project as well.
set(TESTS OFF CACHE BOOL "Switch off CppUTest Test build")
FetchContent_MakeAvailable(CppUTest)

add_executable(
        ${UNITNAME}_tests
        test_files.cpp
        test_main.cpp
)

target_include_directories(
        ${UNITNAME}_tests
        PRIVATE
        ${SWC_PATH}/source
        )


target_link_libraries(
        ${UNITNAME}_tests
        PRIVATE
        CppUTest
        CppUTestExt
        ${UNITNAME}

)

测试文件.cpp:

#include "CppUTest/TestHarness.h"
#include "source_test.h"

TEST_GROUP(FirstTestGroup)
{
};

TEST(FirstTestGroup, print)
{
    hello();

}

test_main.cpp:

#include "CppUTest/CommandLineTestRunner.h"

int main(int ac, char** av)
{
    return CommandLineTestRunner::RunAllTests(ac, av);
}

源目录:

cmake 文件:

cmake_minimum_required(VERSION 3.14.5)
project(test_CPPUTEST)
add_library(
        ${UNITNAME}
        source_test.c
)

source_test.c:

#include <stdio.h>
#include "source_test.h"

void hello() {
    printf("Hello, World!");
}

source_test.h:

#ifndef CPP_U_TEST_SOURCE_H
#define CPP_U_TEST_SOURCE_H


void hello();

#endif //CPP_U_TEST_SOURCE_H

标签: cmake

解决方案


推荐阅读