Share via

LNK2005 error on C++ app when implementing a replacement new and delete

Mike Nice 0 Reputation points
2025-05-30T15:51:20.56+00:00

In Visual Studio 2019 C++14 I can build a "hello world" program with a custom new and delete.

I'm unable to link a larger program which implements a custom new and delete replacement.

The error is

LNK2005 "void * __cdecl operator new(unsigned int)" (??2@YAPAXI@Z) already defined in nafxcw.lib(afxmem.obj)

I've tried all the suggestions listed at

https://stackoverflow.com/questions/1146338/error-lnk2005-new-and-delete-already-defined-in-libcmtd-libnew-obj

Also trying to understand the verbose Link output.

Developer technologies | C++
Developer technologies | C++

A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.

0 comments No comments

2 answers

Sort by: Most helpful
  1. RLWA32 52,566 Reputation points
    2025-05-30T17:25:02.2633333+00:00

    It appears that you are trying to build an MFC application. The MFC framework implements its own custom versions of new and delete. I don't recommend trying to replace the framework's memory management implementation.

    Was this answer helpful?

    1 person found this answer helpful.
    0 comments No comments

  2. Mike Nice 0 Reputation points
    2025-06-24T23:12:02.1266667+00:00

    I studied the problem further by studying the source code afxmem.cpp. I found that because I did not also implement my own version of AFXSetNewHandler(), etc, the MFC library which referenced those functions also caused the MFC versions of new() and delete() operators to be brought in and caused the 'already defined' error.

    Solution: Define custom versions of AfxSetNewHandler()* and then only the custom new() and delete() operators are used by the linker.

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.