先定下结论:
在main文件中使用extern "C"{ }括起来。原因是C++文件与C文件使用编译器不同,编译C++时,会把在C文件中的func1编译成func1@@YAXXZ。
1、环境:
VS2019
已合并的FreeRTOS与LVGLv8一起仿真的工程。
2、问题分析
1)产生
在向已合并的FreeRTOS与LVGLv8一起仿真的工程 中添加应用程序时,出现错误。我已为是没有添加头文件,然鹅,仔仔细细添加后,还是出现此问题。我又将配置中的_CONSOLE程序改成_WINDOWS还是不行。TMD。
2)分析
关键内容如下:
Home > error: LNK2019: unresolved external symbol “void __cdecl fun1(void)” (?fun1@@YAXXZ) referenced in function _main
error: LNK2019: unresolved external symbol “void __cdecl fun1(void)” (?fun1@@YAXXZ) referenced in function _main
Today, I add two c files(one is fun.c, the other is its header file fun.h) to a c++ project, because I want to call a function(fun1) residing in the C source file(fun.c) in a c++ source file (main.cpp) of the C++ project. Then the error occurs.
main.obj:-1: error: LNK2019: unresolved external symbol “void __cdecl fun1(void)” (?fun1@@YAXXZ) referenced in function _main
This error is due to so called name mangling. The C++ compiler compiling main.cpp generates a function reference in main.o, however, the reference is not “fun1” but ?fun1@@YAXXZ, which is called name mangling. When compiling fun.c, the C compiler may generate the function name of fun1 simply as “fun1″(or another mangled name) in fun.o. So, the linker cannot find a match in the function implementation in fun.o for the function reference in main.o, thus reports the error.
意思是:.Cpp与.C使用不同编译器将同一个函数编译成了不同名字。
3)解决方案
方案一:
using C++ compiler to compile the C source file
方案二:
tell C++ compiler not to mangle function names
You can guide the C++ compiler to generate C reference names when compiling main.cpp. Specifically, you can enclose the declaration of the function with extern “C”{…},i.e.,
- #ifdef __cplusplus
- extern "C"{
- #endif
- void fun1( );
- #ifdef __cplusplus
- }
- #endif
This way, the calling of fun1 will simply generate the reference as “fun1″(or other type of C name mangling).
3、结论
在main文件中使用extern "C"{ }括起来。原因是C++文件与C文件使用编译器不同,编译C++时,会把在C文件中的func1编译成func1@@YAXXZ。