0

trying to get cmake working for a small project but keep getting undefined reference to `hello() and checked other threads on what might be wrong but can't figure it out.

The layout of the directories is as follows:

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

source_root cmake file:

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)

tests directory

cmake file:

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}

)

tests_files.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);
}

Source dir:

cmake file:

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

Community
  • 1
  • 1
  • Does adding `extern "C"` in front of `void hello()` in the header file solves the issue? This is needed because you are mixing C and C++. – vre Apr 22 '20 at 08:48
  • In case the comment of @vre does not solve your problem, use the `message` command of CMake to print the current value of `UNITNAME`. If it is empty in your tests `CMakeLists.txt`, you won't link your library. On the other hand, this would mean, that your target name is `_test` and I am not sure if preceding underscores are allowed. But checking the variables content is always a good starting point for debugging. – wychmaster Apr 22 '20 at 08:58
  • extern C solved the issue! thanks for the help :D – Tobias Nilsson Apr 22 '20 at 09:51

0 Answers0