C++ undefined reference to `Function'

I'm having trouble compiling a program using make and c++14

I have three files:

main.cpp
utils.h
utils.c

Inside main.cpp I have:

#include "utils.h"
uint64_t ToolLists::GetAddress(const char* name)
{
    MyObject object;
    return ::FindTest(object, name); //(also tried without ::)
}

Inside utils.h:

uint64_t FindTest(const MyObject object, const char* procName);

Inside utils.c:

uint64_t FindTest(const MyObject exports, const char* procName)
{
    return 0;
}

But on compiling i get the following error and I really don't understand why:

/usr/bin/ld: CMakeFiles/data.dir/main.cpp.o: in function `ToolLists::GetAddress(char const*)':main.cpp:(.text+0x121): undefined reference to `FindTest'

What is wrong with my code?

Any help is appreciated.

EDIT:

What I am trying to do is:

Integrating my c code under json_data inside this project: https://github.com/meltwater/served

Inside examples you can find json_data. and the main.cpp file.

inside the main.cpp I've added the calls to my C functions and also copied utils.h and utils.c there.

The make file is generated by doing from served/ root dir (this command also compile the project) :

mkdir build && cd build && cmake.. && make

Also my utils.h file already have this :

#ifdef __cplusplus
extern "C" {
#endif // 
etc.... 

EDIT:

this is the cmakelists i'm using:

https://github.com/meltwater/served/blob/master/src/examples/json_data/CMakeLists.txt

I've edited it including these two lines of code after "TARGET_LINK_LIBRARIES (json_data ${json_data_LIBS})":

add_library(utils utils.c)
target_include_directories(utils PUBLIC utils.h)

both utils.c and utils.h are in the same directory.

is that the correct procedure?

EDIT:

Solved with the following CMakeLists file.

FILE (GLOB_RECURSE json_data_SRCS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp ${CMAKE_CURRENT_SOURCE_DIR}/*.hpp)

SET (json_data_LIBS ${PROJECT_NAME} ${Boost_LIBRARIES} ${CMAKE_THREAD_LIBS_INIT})


ADD_EXECUTABLE (json_data ${json_data_SRCS})

add_library(utils utils.c)

set(HEADER_FILES utils.h)

TARGET_LINK_LIBRARIES (json_data ${json_data_LIBS} utils)

INSTALL (TARGETS json_data DESTINATION bin)

1 answer

  • answered 2019-12-14 18:17 xibu

    C++ decorates function-names with type information about their parameters.

    If you want to call functions that are defined in C from C++ you have to use extern "C" (how does extern "C" work).

    Try changing your header to

    ...
    #ifdef __cplusplus
    extern "C"
    {
    #endif
    
    // declarations of the functions you want to define in c
    
    #ifdef __cplusplus
    }
    #endif
    ...