简体   繁体   中英

xcode c/c++ linker error: undefined symbol

I did some search but my problem seems to be trivial so that no one asked.
I have a mixed c and c++ code.

In model.h , I have the following declaration:

void free_and_null (char **ptr);

In model.cpp , I have the function body:

void free_and_null (char **ptr)
{
    if ( *ptr != NULL ) {
        free (*ptr);
        *ptr = NULL;
    }
} /* END free_and_null */

In a solve.c file, I have the following :

#include "sort.h"
.....
    free_and_null ((char **) &x);

When I compile the project, it has the following linker error:

wrap) Undefined symbols for architecture x86_64: "_free_and_null", referenced from:

Why such a simple program can have error? I use Apple LLVM 6.0 as the compiler. Any input is highly appreciated.

You need to tell the C++ compiler that the function should have "C" linkage by declaring it as such (in your C++ source file).

extern "C" {
  void free_and_null (char **ptr);
}

C++ compilers construct "mangled" names for functions so that two functions with the same name but different argument types end up having different mangled names; that's necessary because linkers expect all names to be unique. Consequently, the code generated by the C++ compiler in your example will produce a different name than the name produced by the C compiler. (On Intel platforms, C compilers also modify names slightly, by prefixing an underscore, which is why it complains that _free_and_null is unfound.)

One common way of doing this is to make a header file which uses preprocessor macros to detect the language. It's not fully portable, but it should work in your case:

// File model.h
// This will not work with all C++ compilers, but it works with clang and gcc
#ifdef __cplusplus
extern "C" {
#endif

void free_and_null (char **ptr);
// Other function declarations here

#ifdef __cplusplus
}
#endif

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM