c++cvisual-studio-2010externlnk2001

Linker error when calling a C function from C++ code in different VS2010 project


I'm trying to include some C code I found in our C++ project. The function is defined like this in the C file.

#ifdef __cplusplus
extern "C" {
#endif
 extern char *dtoa(double, int, int, int *, int *, char **);
 extern char *g_fmt(char *, double);
 extern void freedtoa(char*);
#ifdef __cplusplus
    }
#endif

 char *
g_fmt(register char *b, double x)
{

The VS project I'm including this in is creating a dll. The file is being compiled as C, other files in the project are being compiled as C++.

I added a header to include in my C++ files

#ifndef G_FMT_H
#define G_FMT_H
#ifdef __cplusplus
extern "C" {
#endif
 extern char *dtoa(double, int, int, int *, int *, char **);
 extern char *g_fmt(char *, double);
 extern void freedtoa(char*);

#ifdef __cplusplus
}
#endif
#endif //G_FMT_H

In another project in the solution I include my header and try calling the g_fmt function.

#include "header.h"
...
g_fmt(my_array, 2.0);

This project is linking to the other one, I'm able to call C++ functions in the first library without any issues. However, adding the above line gives me a lnk2001 error .

error LNK2001: unresolved external symbol g_fmt

I've found a number of other questions about mixing C and C++ and I seem to have done everything necessary with the extern keywords in the right places, however I'm still not able to link. Is there anything specific I need to do in VS2010?


Solution

  • The question is for VStudio 2010, but applies to any version.

    In C or C++, considering that a module may consist of multiple objects, every object should be clearly delimited. Also, every object (.c or .cpp file) should have its own header file. So, you should have one header file and one .c(xx) file for the C functions (3 in your example).
    Also, as a general guideline, try to be consistent when naming files and macros: your header.h file uses G_FMT_H macro as include guard.
    Try reorganizing your .h and .c files to something like:

    2 things to notice here (besides reorganizing and renaming) in the header file:

    Similar (or related) issues: