17

我有在 GNUARM 编译器上编译的代码,但 Visual Studio 2010 出现错误。该问题涉及在 C 语言文件中的第一条语句之后声明变量:

主程序

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

int main(void)
{
  int i = 6;
  i = i + 1;
  printf("Value of i is: %d\n", i);
  int j = i * 10; // <-- This is what Visual Studio 2010 complains about.
  printf("Value of j is: %d\n", j);
  return EXIT_SUCCESS;
}

以下代码编译没有错误:

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

int main(void)
{
  int i = 6;
  int j;      // <-- Declaration is now here, valid according to K&R rules.
  i = i + 1;
  printf("Value of i is: %d\n", i);
  j = i * 10; // <-- Moved declaration of j to above.
  printf("Value of j is: %d\n", j);
  return EXIT_SUCCESS;
}

我正在使用默认设置来创建 Win32 控制台项目。当我将“编译为”属性设置为“编译为 C++ (/TP)”时,在一些 Visual Studio 头文件中出现编译错误。(右键单击项目,选择PropertiesConfiguration PropertiesC/C++Advanced)。

如何告诉 Visual Studio 2010 在第一条语句之后允许变量声明,如 C++ 或当前的 C 语言标准?

4

3 回答 3

9

你没有。Visual C++ 不支持 C99。

您需要编译为 C++(并相应地更新您的代码)或遵循 C89 的规则。

(我不知道您在编译时会遇到什么错误;如果我添加for /TP,我可以成功编译您的示例;如果您提供更多详细信息,我或其他人可能会提供帮助。)/TP#include <stdlib.h>EXIT_SUCCESS

于 2011-09-30T18:20:04.210 回答
6

从 Visual Studio 2013 开始,Visual C++ 编译器支持 C99 样式的变量声明。更多详情可参见:

http://blogs.msdn.com/b/vcblog/archive/2013/06/28/c-11-14-stl-features-fixes-and-break-changes-in-vs-2013.aspx

于 2014-08-14T22:54:24.840 回答
2

我使用默认的 Visual Studio 2010 项目,使用 C 文件和/TP开关进行了相同的测试,并得到了预编译头错误。可以通过重命名stdafx.cppstdafx.c或禁用整个项目或特定 C 文件的预编译头文件来删除它。

我没有发现任何其他问题。但是,这有效地将 C 语言转换为 C++,我认为这不是您的意图。但是,C 允许在每个{}块的开头定义一个变量。

于 2011-09-30T18:36:36.850 回答