'Compilation error C2048 while compiling in visual studio 2019 MSVC, but works fine with clang++?

I tried to compile the following sample code with clang compiler and it works fine.

  • Compiler Details: Apple clang version 12.0.0 (clang-1200.0.32.28)
  • Target: x86_64-apple-darwin20.1.0
#include <iostream>
#include <stdio.h>

int __cdecl printf(const char* format, ...)
{
    std::cout<<"My printf function"<<std::endl;
    return 0;
}

int main()
{
    printf("Standard printf function\n");
    return 0;
}

However, when I tried to compile it in visual studio 2019, it gives a compilation error.

error C2084: function 'int printf(const char *const ,...)' already has a body

  • What is the reason for compilation failure with MSVC?
  • How can I make it work, what am I missing?
    My goal is to implement my version of printf() function, but wants to use other standard function available in stdio.h. How can I achieve that with MSVC?


Solution 1:[1]

From your code you are intentionally trying to use your own version of the printf function.

The error C2084 is expected. You are redefining something already defined. It's dangerous, and you be aware of the risks you are taking. It's a piece of a whole library and any UB (undefined Behaviour) may arise. I won't play with that. From my perspective it's g++ that is not reporting an error, but it may be that the g++/libc prototype of printf is slightly different from the one you wrote, or even, the function printf is declared in the header but not defined in there.

If you really want go down that way I strongly suggest you to define your printf in another source file and hide the libc implementation at linking time. That should be allowed (Warning and errors may arise, but every linker has an override for that).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dharman