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

标签 c++ c compiler-errors visual-studio-2019 clang++

我尝试使用 clang 编译器编译以下示例代码,它工作正常。

  • 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;
}
但是,当我尝试在 Visual Studio 2019 中编译它时,它给出了编译错误。

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


  • MSVC编译失败的原因是什么?
  • 我怎样才能让它工作,我错过了什么?
    我的目标是实现我的 printf() 函数版本,但想使用 stdio.h 中可用的其他标准函数。如何使用 MSVC 实现这一目标?
  • 最佳答案

    从您的代码中,您有意尝试使用您自己的 printf 版本。功能。
    预计会出现错误 C2084。您正在重新定义已经定义的东西。这很危险,你要意识到你所承担的风险。它是整个库的一部分,可能会出现任何 UB(未定义行为)。我不会玩那个。从我的角度来看,是 g++ 没有报错,但可能是 printf 的 g++/libc 原型(prototype)与您编写的略有不同,甚至函数 printf 是在 header 中声明但未在其中定义。
    如果你真的想这样下去,我强烈建议你定义你的 printf在另一个源文件中并在链接时隐藏 libc 实现。这应该是允许的(可能会出现警告和错误,但每个链接器都有一个覆盖)。

    关于c++ - 在 Visual Studio 2019 MSVC 中编译时出现编译错误 C2048,但在 clang++ 中可以正常工作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65737350/

    相关文章:

    c - ifdef 和 solaris

    .net - 阻止将特定的程序集添加到我的工厂项目中?

    java - 我可以实例化一个开关吗?或者说这有什么问题吗?

    c++ - 避免对实现接口(interface)的类进行多个几乎相同的声明

    c - 需要有关评估给定表达式的解释

    发送 EOF 后无法读取任何内容?

    具有 2 个操作的单行 if 语句的 C# 编译器错误

    浮点的 C++ 模板特化

    c++ - VS : unexpected optimization behavior with _BitScanReverse64 intrinsic

    c++ - 使用 make_pair(_Ty1&& _Val1, const _Ty2& _Val2) 在 C++11 中进行重大更改