Ld: error: undefined symbol:

I have an existing project that builds just fine.
I need to add a function. When I add it to an existing file the project builds fine.
When I add it to a new file, the output shows the file is compiled, but the linker can’t find it.
Does anyone have any idea where to look to fix this?
I’m sure it’s a minor issue in the setup but I can’t find it despite looking for a couple of hours.

The linker error:

ld: error: undefined symbol: main_vm(int, char**)
>>> referenced by native-lib.cpp:41 

The new function in .h file:

int main_vm(int argc, char **argv); 

The new header in .cfile:

int main_vm(int argc, char **argv){
   // empty
}

CMakeLists.txt:

set(HEADER_FILES
    atom.h.  // the project builds when the function is added here.
    vmstart.h // the linker error shows up when the function definiton is added here.
)

set(SOURCE_FILES
    atom.c // the project builds when the function implementation is added here.
    vmstart.c  // the linker error shows up when the function implementation is added here.
)


Thanks in advance.

Your error message has a .cpp file, but the CMakeLists.txt example has .c files. The difference is important here :slight_smile: C++ does name mangling while C doesn’t, so function names will be different between the two. If you want to define a function in a C source file and use it from a C++ source file, the simplest way is to declare it as extern "C" in your header, as follows:

#ifdef __cplusplus
extern "C" {
#endif

// regular declarations here

#ifdef __cplusplus
} // extern "C"
#endif

Note that this goes in the header file around the declaration of your function, not in the source file (which is already C, and thus won’t recognize extern "C"). The #ifdef __cplusplus check is to make the header usable from both C and C++ source files.