Resolving Linker Errors in Mixed C and C Projects in VS2010
Issue Description
Integrating C code into a C project in different VS2010 projects has resulted in a link error when calling a C function from C code. The error, identified as LNK2001, pertains to an unresolved external symbol.
Solution
To rectify this issue, ensure proper organization of the codebase by adhering to specific guidelines:
-
Modularize Code:
- Each C module should comprise one header file and one source file.
- Maintain consistency in naming conventions for both files and macros.
-
Create Headers and Implementation Files:
- Define functions in header files (e.g., functions.h) and implement them in source files (e.g., functions.c).
-
Manage Exports and Imports:
- Utilize the FUNCTIONS_EXPORT_API macro to mark functions for export (or import) in the header file.
- When including the header in the project that uses the functions, do not define FUNCTIONS_EXPORT_API (or define the macro with its import value).
- Ensure that the project exporting the functions has the FUNCTIONS_EXPORT macro defined (automatically or manually) before including the header.
Example Code
functions.h
<code class="c">#pragma once
#define FUNCTIONS_EXPORT_API
#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>
Copy after login
functions.c
<code class="c">#define FUNCTIONS_EXPORTS
#include "functions.h"
char *dtoa(double, int, int, int*, int*, char**)
{
// Function implementation
}
char *g_fmt(char*, double)
{
// Function implementation
}
void freedtoa(char*)
{
// Function implementation
}</code>
Copy after login
Additional Considerations
- Avoid using the extern storage specifier in function declarations within the header.
- Utilize the project-specific macro (e.g., EXPORTFUNCTIONSPROJECT_EXPORTS) to automate exports.
- Verify the macro names in the project properties under Preprocessor Definitions.
Related Issues
- [LNK2005 Error in CLR Windows Form](https://stackoverflow.com/a/17362530/1128974)
- [Excel VBA, Can't Find DLL Entry Point from a DLL file](https://stackoverflow.com/a/7214325/1128974)
- [When using fstream in a library I get linker errors in the executable](https://stackoverflow.com/a/10068252/1128974)
- [C dll export undefined](https://stackoverflow.com/a/7709927/1128974)
The above is the detailed content of How to Resolve LNK2001 Linker Errors in Mixed C and C Projects in VS2010?. For more information, please follow other related articles on the PHP Chinese website!