GCC:使用旧 C 代码时的链接器错误
GCC: linker error when working with old C code
我在使用GCC编译器时遇到了一个神秘的情况。所以我有以下文件:
主.cpp
#include "mleak_cpp.h"
int main(int argc, char* argv[])
{
foo();
__memory_malloc(10,"hello",5);
return 0;
}
//mleak_cpp.h
......
void foo(void);
void* __memory_malloc(size_t size, const char* file, int line);
//mleak_cpp.cpp
//definitions of the functions;
void foo(void){printf("foon");
void* __memory_malloc(size_t size, const char* file, int line){
printf("%s,%dn",file,line);
InitDoubleLinkList();
void* p = malloc(size);
if(p == NULL)
return NULL;
__DuLinkList* pListNode;
pListNode = (__DuLinkList*)malloc(sizeof(__DuLinkList));
pListNode->address = p;
pListNode->memorysize = size;
pListNode->file = file;
pListNode->line = line;
InsertBlockToList(pListNode);
return p;
}
出于某种原因,对void foo(void)的调用很好,但是对"__memory_malloc"的调用会因链接器错误而下降,"未定义的引用"等等。导致不同行为的两个函数之间有什么区别?
我尝试将"extern C"添加到"#include"指令中,因此main.cpp为:
extern "C"{
#include "mleak_cpp.h"
}
并在函数声明之前添加关键字"extern",这次对"foo()"的调用也失败并出现相同的错误。
我感谢你们的任何帮助
extern "C"
放在了错误的地方。
如果main.c
确实是一个 C 文件,并且mleak_cpp.cpp
确实是一个C++函数,那么你需要在__memory_malloc()
的定义之前放一个extern "C"
,如下所示:
extern "C" void* __memory_malloc(size_t size, const char* file, int line){
// ...
}
如果将extern "C"
放入mleak_cpp.h
文件中,则需要对其进行保护:
#ifdef __cplusplus
extern "C" {
#endif
/* ... body of header ... */
#ifdef __cplusplus
}
#endif
此外,不清楚为什么foo
在上面的示例中工作,当一个文件调用__foo()
但另一个文件定义foo()
时。 我认为还有更多的东西在起作用,例如您的问题中的编辑错误。
extern "C"
用于C++,而不是C,并告诉它函数的名称不应该被破坏。在 C 代码中,你不应该看到这个。通常,您将它放在头文件中,并对其进行保护,如下所示:
#ifdef __cplusplus
extern "C" {
#endif
/* C and C++ compatible header file body here */
#ifdef __cplusplus
} /* end extern "C" */
#endif
但是,如果这样做,则需要将头文件包含在 C 和 C++ 文件中,以便C++编译器知道使用 C 链接。
您可以将extern "C"
放在 C++ 中的函数定义前面,并将其排除在标头之外,但这仅在 C 代码中包含标头时才有效,因此建议按照我上面指出的方式进行操作。
- 静态数据成员的问题-修复链接错误会导致编译器错误
- Visual Studio mkl_link_tool.exe链接错误
- C++ 实现模板单例类时出现链接错误
- 使用类模板的方法链接错误
- MySQL C++连接器链接错误
- VS 2015 链接错误 无法构建依赖于 libcurl 的项目
- 运行 C++ 单元测试时LNK2005链接错误
- 对 CMake 中'cudaRegisterLinkedBinary'链接错误的未定义引用?
- 链接错误,包括我创建的相同头文件 - C++
- 在Embarcadero C++ Builder中生成的DLL未解决的外部链接错误
- 使用标头保护的多个定义链接错误
- 链接错误:未定义对 stdscr 和 wgetch 的引用
- 使用 Vivek 的 Vcam / 捕获源过滤器构建/链接错误
- 升压program_options中的链接错误
- 使用 g++ 预处理器进行替换会导致链接错误
- 在调试配置中编译工作正常,但发布会给出链接错误
- 相邻矩阵设置链接错误
- 包含常量变量并包含在多个文件中的标头的链接错误
- C++链接错误,我理解但无法解决
- 是什么导致macOS Mojave上的GoogleTest链接错误