1

the following code produces this error:

error LNK2019: unresolved external symbol "char const * __cdecl nameOnly(char const *)"

Code:

const char* nameOnly(const char* namewpath)
{
    const char* res = namewpath + strlen(namewpath);
    while (res > namewpath) {
        const char* tmp = res - 1;
        if (*tmp == '/' || *tmp == '\\') break;
        --res;
    }
    return res;
}

the above code is a plain c file and I'm compiling it with visual-C++. I don't get this error, when compiling with C-compiler.

UPDATE: I have tried using extern:

extern "C"{ 
 const char* nameOnly(const char* namewpath)
 {
    ...
    }
    return res;
 }
}

and I get this error:

error C2059: syntax error : 'string'
RayOldProf
  • 1,040
  • 4
  • 16
  • 40

3 Answers3

2

Sounds like a difference between the function declaration and the function definition.

And when you say "this code is plain C", it's only plain C if the declaration is surrounded with extern C { ... } when the header file is included from a C++ implementation file, otherwise name mangling comes into play, which is what I believe this error is about.

trojanfoe
  • 120,358
  • 21
  • 212
  • 242
2

You need to use a header file that marks the function as extern "c" when compiling your code as part of a C++ project.

Inside nameOnly.h:

#ifdef __cplusplus
extern "C"{
#endif

const char* nameOnly(const char* namewpath);

#ifdef __cplusplus
}
#endif

Then inside nameOnly.c:

const char* nameOnly(const char* namewpath)
{
    const char* res = namewpath + strlen(namewpath);
    while (res > namewpath) {
        const char* tmp = res - 1;
        if (*tmp == '/' || *tmp == '\\') break;
        --res;
    }
    return res;
}

Now when some cpp file includes nameOnly.h, the function will be marked as extern "C" properly.

Gregory Pakosz
  • 69,011
  • 20
  • 139
  • 164
  • The `extern "C"` should be on the function declaration, not the definition, otherwise it has no effect (if this is a `.c` file when it's illegal, and if it's `.cpp` then it will work as expected). – trojanfoe Sep 05 '13 at 12:51
  • Yep I was in the middle of phrasing what I meant properly – Gregory Pakosz Sep 05 '13 at 12:54
2
extern "C"

will solve your problem of linkage because it tells the C++ compiler that a C compiler will also need to access this function but a C compiler does not understand this use of extern.

If you want to solve it you can do something like:

In your header file:

#ifdef __cplusplus
extern "C"{
#endif

const char* nameOnly(const char* namewpath);

#ifdef __cplusplus
}
#endif

and in your .c file:

const char* nameOnly(const char* namewpath)
{
    const char* res = namewpath + strlen(namewpath);
    while (res > namewpath) {
        const char* tmp = res - 1;
        if (*tmp == '/' || *tmp == '\\') break;
        --res;
    }
    return res;
}
Pierre Fourgeaud
  • 14,290
  • 1
  • 38
  • 62