Introduction
I'm currently trying to start a C project on a devcontainer. Inside this project: GoogleTest with CMake.
I have added the googletest folder inside my project with a clone of the github project.
The Dockerfile of the devcontainer:
FROM mcr.microsoft.com/devcontainers/cpp:0-ubuntu-22.04
ARG REINSTALL_CMAKE_VERSION_FROM_SOURCE="3.22.2"
# Optionally install the cmake for vcpkg
COPY ./reinstall-cmake.sh /tmp/
RUN if [ "${REINSTALL_CMAKE_VERSION_FROM_SOURCE}" != "none" ]; then \
chmod +x /tmp/reinstall-cmake.sh && /tmp/reinstall-cmake.sh ${REINSTALL_CMAKE_VERSION_FROM_SOURCE}; \
fi \
&& rm -f /tmp/reinstall-cmake.sh
# Add googletest and cmake
RUN apt-get update && sudo apt-get update && sudo apt-get install -y build-essential libgtest-dev
The CMakeLists.txt:
cmake_minimum_required(VERSION 3.14)
project(Piscine-42)
# GoogleTest requires at least C++14
set(CMAKE_CXX_STANDARD 14)
# set for C
set(CMAKE_C_STANDARD 99)
add_subdirectory(googletest) # add googletest subdirectory
include_directories(googletest/include) # this is so we can #include <gtest/gtest.h>
add_executable(test_return_one test_return_one.cpp) # add this executable
target_link_libraries(test_return_one PRIVATE gtest) # link google test to this executable
The tested code return_one.c:
#include "return_one.h"
int return_one(void)
{
return (1);
}
return_one.h:
#include "return_one.h"
int return_one(void)
{
return (1);
}
The code for tests test_return_one.cpp:
#include "gtest/gtest.h"
extern "C" {
#include "return_one.h"
}
TEST(t_return_one, returns_1)
{
EXPECT_EQ(1,return_one());
}
int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
Problem
The problem, when I'm running the code with CMake-tools VSCode extension, I obtain this error:
[main] Building folder: Piscine-42 test_return_one
[build] Starting build
[proc] Executing command: /usr/local/bin/cmake --build /workspaces/Piscine-42/build --config Debug --target test_return_one --
[build] [1/1 100% :: 0.266] Linking CXX executable test_return_one
[build] FAILED: test_return_one
[build] : && /usr/bin/g++ -g CMakeFiles/test_return_one.dir/test_return_one.cpp.o -o test_return_one lib/libgtest.a && :
[build] /usr/bin/ld: CMakeFiles/test_return_one.dir/test_return_one.cpp.o: in function `t_return_one_returns_1_Test::TestBody()':
[build] /workspaces/Piscine-42/test_return_one.cpp:9: undefined reference to `return_one'
[build] collect2: error: ld returned 1 exit status
[build] ninja: build stopped: subcommand failed.
[proc] The command: /usr/local/bin/cmake --build /workspaces/Piscine-42/build --config Debug --target test_return_one -- exited with code: 1 and signal: null
[build] Build finished with exit code 1
Question
Does someone know how we can fix it?
The GitHub repo with full project : GitHub Repo.