简体   繁体   English

VS2012中的C ++自定义内存分配链接错误

[英]C++ Custom memory allocation link error in VS2012

I get the following linker error when I try to override the default memory allocation functions in VS2012: 当我尝试覆盖VS2012中的默认内存分配函数时,出现以下链接器错误:

1>Main.obj : error LNK2005: "void * __cdecl operator new(unsigned int)" (??2@YAPAXI@Z) already defined in MSVCRTD.lib(MSVCR110D.dll) 1>Main.obj : error LNK2005: "void __cdecl operator delete(void *)" (??3@YAXPAX@Z) already defined in MSVCRTD.lib(MSVCR110D.dll) 1>c:\\users\\documents\\visual studio 2012\\Projects\\CustomMemoryAllocator\\Debug\\CustomMemoryAllocator.exe : fatal error LNK1169: one or more multiply defined symbols found 1> Main.obj:错误LNK2005:“ void * __cdecl运算符new(unsigned int)”(?? 2 @ YAPAXI @ Z)已在MSVCRTD.lib(MSVCR110D.dll)中定义1> Main.obj:错误LNK2005:“ void __cdecl运算符delete(void *)”(?? 3 @ YAXPAX @ Z)已在MSVCRTD.lib(MSVCR110D.dll)1> c:\\ users \\ documents \\ visual studio 2012 \\ Projects \\ CustomMemoryAllocator \\ Debug \\ CustomMemoryAllocator中定义。 exe:致命错误LNK1169:找到一个或多个乘法定义的符号

Here is my code (I get no intellisense errors): 这是我的代码(我没有智能感知错误):

#include <iostream>

using namespace std;

void *operator new(size_t size){
    if(void *mem = malloc(size)){
        cout << "allocated memory" << endl;
        return mem;
    }
    else{
        throw bad_alloc();
    }
}

void operator delete(void* mem) throw() {
    cout << "deleting" << endl;
    free(mem);
}

int main(){
    cout << "test";
    int* a = new int(4);
    delete a;
    int b = 0;
    cin >> b;
}

Could someone please help? 有人可以帮忙吗?

Libraries not getting linked in correct order 图书馆未按正确的顺序链接

Trying adding at top of your file 尝试在文件顶部添加

#pragma comment(linker, "/nodefaultlib:libc.lib")
#pragma comment(linker, "/nodefaultlib:libcd.lib")

Else follow these instructions. 否则,请遵循以下说明。

Try using a DLL instead of static linking the libraries. 尝试使用DLL而不是静态链接库。 Go to project properties / C++ / Code Generation / Runtime Library and pick the DLL option. 转到项目属性/ C ++ /代码生成/运行时库,然后选择DLL选项。

Windows calls a DLL or EXE a module. Windows将DLL或EXE称为模块。 A module is not allowed to multiply define a symbol, but two different modules used by one process can define the same symbol. 不允许一个模块多次定义符号,但是一个进程使用的两个不同模块可以定义同一符号。 When using a DLL, operator new() is defined in both your and the MSVC module which causes no error. 使用DLL时,在您和MSVC模块中都定义了运算符new(),这不会导致任何错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM