gpt4 book ai didi

c++ - 为什么这个 C 代码在 Codeblocks 中编译,而不是在 Visual Studio 中编译?

转载 作者:太空狗 更新时间:2023-10-29 23:29:43 25 4
gpt4 key购买 nike

当我尝试使用默认 C/C++ 设置在 Visual Studio 2017 上编译以下 C 代码时:

#include <stdio.h>
#include <stdlib.h>


/* function declaration */
/*Line 6*/ int max(int num1, int num2, int num3);

int main() {

/* local variable definition */
int a = 100;
int b = 200;
int c = 400;
int ret;

/* calling a function to get max value */
ret = max(a, b, c);
printf("Max value is : %d\n", ret);
return 0;
}

/* function returning the max between two numbers */
/*Line 25*/ int max(int num1, int num2, int num3) {

/* local variable declaration */
int result;

if (num1 > num2)
result = num1;
else
result = num3;
return result;
}

我收到错误:

需要一个标识符:第 6,25 行

应为“;”:第 25 行

Intellisense 突出显示这些行,不会让我运行代码。然而在 Codeblocks 中(使用默认的 GNU GCC 编译器,来自 mingW)这个精确的代码编译得很好。是什么原因造成的?

多个消息来源告诉我,这不是因为使用 GCC 编译器的 Codeblocks和 Visual Studio 默认使用“cl”编译器。

同样的消息来源告诉我,这也不是因为每个 IDE 都可能使用不同的 C 标准编译代码。

我已将文件扩展名命名为“.c”,但出现了这些错误

如果我尝试将代码编译为 c++(或“.c++”文件,它可以工作,但这不是我想要的。我要 C。

我更愿意使用 Visual Studio 而不是 Codeblocks,因为它的外观和菜单布局都很时尚。我也更喜欢 Visual Studio 调试器。

我可以采取哪些步骤在 Visual Studio 2017 上成功编译这个简单的代码?

最佳答案

Microsoft 有一个众所周知的定义 max macro .如果出于某种原因将宏定义拉入您的源代码,则标记替换将造成严重破坏。我打赌的结果就是你所看到的。主要是因为您自己承认,它只发生在 Visual Studio 中。

解决方案(及其测试)相当简单。其中之一应该“修复”您的代码:

  1. max 重命名为其他名称,例如 my_max
  2. 在包含任何 header 之前,添加 #define NOMINMAX 以禁止在任何包含的 MS header 中定义宏。

除此之外,您将不得不修改项目设置并查看可能设置不当的地方。这不是一个应该自动添加到简单控制台项目中的宏。

关于c++ - 为什么这个 C 代码在 Codeblocks 中编译,而不是在 Visual Studio 中编译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51007933/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com