GCC:使用旧 C 代码时的链接器错误

GCC: linker error when working with old C code

本文关键字:链接 错误 代码 GCC      更新时间:2023-10-16

我在使用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 代码中包含标头时才有效,因此建议按照我上面指出的方式进行操作。