coderbhai
coderbhai

Reputation: 41

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

Upvotes: 0

Views: 223

Answers (1)

Stefano Buora
Stefano Buora

Reputation: 1062

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).

Upvotes: 0

Related Questions