简体   繁体   English

在 Visual Studio 中编译时出现编译错误 C2048,但在 clang++ 中可以正常工作吗?

[英]Compilation error C2048 while compiling in visual studio, but works fine with clang++?

I tried to compile the following sample code with clang compiler and it works fine.我尝试使用 clang 编译器编译以下示例代码,它工作正常。

  • Compiler Details: Apple clang version 12.0.0 (clang-1200.0.32.28)编译器详细信息:Apple clang 版本 12.0.0 (clang-1200.0.32.28)
  • Target: x86_64-apple-darwin20.1.0目标: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 in visual studio 2019 or g++, it gives compilation error.但是,当我尝试在 Visual Studio 2019 或 g++ 中编译时,会出现编译错误。

error C2084: function 'int printf(const char *const,...)' already has a body错误 C2084: function 'int printf(const char *const,...)' 已经有正文

  • What is the reason of compilation failure with msvc? msvc编译失败的原因是什么?
  • How can I make it work, what am I missing?我怎样才能让它工作,我错过了什么?

From your code you are intentionally trying to use your own version of the printf function.从您的代码中,您有意尝试使用您自己的printf function 版本。

The error C2084 is expected.预计会出现错误 C2084。 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.它是整个库的一部分,可能会出现任何 UB(未定义行为)。 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. 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.如果你真的想要 go 那样我强烈建议你在另一个源文件中定义你的printf并在链接时隐藏 libc 实现。 That should be allowed (Warning and errors may arise, but every linker has an override for that).这应该是允许的(可能会出现警告和错误,但每个 linker 都有一个覆盖)。

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

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