0

I have a simple project, which consists of several directories with sources and CMakeLists.txt files.
Here is my project structure:

CMakeLists.txt\
main.c

src/source1.c\
src/source1.h\
src/CMakeLists.txt

test/test.cpp\
test/main.cpp\
test/CMakeLists.txt

googletest

Main executable has been built successfully, but test executable not, linker errors instead (undefined references to functions from src directory). Here is my CMake files content:

CMakeLists.txt:

cmake_minimum_required(VERSION 3.22)
project(TIC-TAC-TOE)

set(CMAKE_C_STANDARD 99)

set(CXXMAKE_C_STANDARD 11)
set(POSITION_INDEPENDENT_CODE ON)

enable_testing()

include_directories(src)
add_subdirectory(test)
add_subdirectory(src)
add_subdirectory(googletest)

add_executable(TIC-TAC-TOE main.c)

target_link_libraries(TIC-TAC-TOE tic_tac_toe-lib)

src/CMakeLists.txt:

set(Sources tic-tac-toe.c tic-tac-toe.h)

add_library(tic_tac_toe-lib STATIC ${Sources})

test/CMakeLists.txt:

project(TIC-TAC-TOE-TEST)

set(Sources tic-tac-toe-test.cpp
    main.cpp
    )

add_executable(TIC-TAC-TOE-TEST ${Sources})


add_test(
    NAME TIC-TAC-TOE-TEST
    COMMAND TIC-TAC-TOE-TEST
    )
    
target_link_libraries(TIC-TAC-TOE-TEST PUBLIC tic_tac_toe-lib gtest_main)
  • 1
    Show the errors and show the code. You are trying to link a C lib into a C++ object for the test executable (compared with the main executable which is C). That can work but needs the lib header to support inclusion into both C and C++ source. That's why we need to see the code. – kaylum Oct 24 '21 at 21:10
  • @kaylum I include `tic-tac-toe.h` in `tic-tac-toe-test.cpp` and use functions which has a declarations in `tic-tac-toe.h` file. I get undefined reference errors to this particular functions... The implementation of that functions are in `tic-tac-toe.c` file. The code is not so small... Which file do you need to see? – MichaelPhoenix Oct 24 '21 at 22:31
  • Then create a [mre]. We need to see complete code that can repro the problem as by definition we can't know for sure where the problem is without that and hence can't tell you exactly which file to show. But likely you are missing `extern C` in tic-tac-toe.h. Do you understand in general what needs to be done to call a C function from C++ code? If not then that's what you need to research. – kaylum Oct 24 '21 at 22:34
  • @kaylum Oh, I remember such a problem when including C code into C++, but completely forgot about it now... I am 99% sure that it is just what I need. Thank you! – MichaelPhoenix Oct 24 '21 at 22:39
  • Not just `extern` but `extern "C"`. See: https://stackoverflow.com/questions/1041866/what-is-the-effect-of-extern-c-in-c. And you need to do that only if it is being included into a C++ source file. That is, if included in C source file then don't add that. One way is to use `#ifdef __cplusplus` – kaylum Oct 24 '21 at 22:42

0 Answers0