Understanding the Issue:
A developer encountered a linker error when attempting to call a C function from a C project in a different Visual Studio 2010 solution. Despite using extern keywords and including a header, the project failed to link to the C library, resulting in an "unresolved external symbol" error.
Correcting the Structure:
To resolve the issue, the project structure for the C functions needs to be reorganized and renamed. Instead of including the C function definitions in the header, the header should simply declare extern functions with the correct calling conventions. The implementation of these functions should be moved to a separate C source file.
Exporting Functions:
Exporting the C functions is done by defining a macro in the C source file. When the project is compiled, this macro defines the functions as exported. In the C project, the header should be included first to define the extern functions, followed by appropriate macros to mark the functions as imported.
Suggested File Structure:
Example Files:
functions.h
<code class="c">#pragma once #if defined(_WIN32) #if defined(FUNCTIONS_STATIC) #define FUNCTIONS_EXPORT_API #else #if defined(FUNCTIONS_EXPORTS) #define FUNCTIONS_EXPORT_API __declspec(dllexport) #else #define FUNCTIONS_EXPORT_API __declspec(dllimport) #endif #endif #else #define FUNCTIONS_EXPORT_API #endif #if defined(__cplusplus) extern "C" { #endif FUNCTIONS_EXPORT_API char *dtoa(double, int, int, int*, int*, char**); FUNCTIONS_EXPORT_API char *g_fmt(char*, double); FUNCTIONS_EXPORT_API void freedtoa(char*); #if defined(__cplusplus) } #endif</code>
functions.c
<code class="c">#define FUNCTIONS_EXPORTS #include "functions.h" char *dtoa(double, int, int, int*, int*, char**) { //function statements } char *g_fmt(char*, double) { //function statements } void freedtoa(char*) { //function statements }</code>
By implementing these changes, the linker error should be resolved, and the C project will be able to successfully link to and call the C functions defined in the separate project.
The above is the detailed content of How to Resolve Linker Errors When Calling C Functions from a Separate C Project in Visual Studio 2010?. For more information, please follow other related articles on the PHP Chinese website!