1

我正在尝试使用 cl.exe(64 位命令行)在 VS2010 Professional 中编译 C 程序。在 VS2010 或 VS2008 中出现奇怪的错误。相同的代码在 GNU gcc 中编译和运行没有问题(Cygwin)。有任何想法吗?在我理解这里的问题之前,无法进一步了解真实的东西。谢谢!

文件名:testC.c

cl.exe testC.c

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

typedef double Td;

int main(int argc, char *argv[])
  {
      FILE *fp;
      if ( (fp=fopen("junk_out.txt","w")) == NULL ){
                printf("Cannot open file.\n");
                exit(1);
      }
      fprintf(fp,"%f \n",3.1420);
      fclose(fp);
      Td x=3.14;
      Td *a;
      a = &x;
      printf("%f \n",a);
      printf("%f \n",x);
      printf("%f \n",*a);

      return 0;
   }

这是输出:

      testC.c(18): error C2275: 'Td' : illegal use of this type as an expression
      testC.c(5) : see declaration of 'Td'
      testC.c(18): error C2146: syntax error : missing ';' before identifier 'x'
      testC.c(18): error C2065: 'x' : undeclared identifier
      testC.c(18): warning C4244: '=' : conversion from 'double' to 'int', possible loss of data
      testC.c(19): error C2275: 'Td' : illegal use of this type as an expression
      testC.c(5) : see declaration of 'Td'
      testC.c(19): error C2065: 'a' : undeclared identifier
      testC.c(21): error C2065: 'a' : undeclared identifier
      testC.c(21): error C2065: 'x' : undeclared identifier
      testC.c(21): warning C4047: '=' : 'int' differs in levels of indirection from 'int *'
      testC.c(22): error C2065: 'a' : undeclared identifier
      testC.c(23): error C2065: 'x' : undeclared identifier
      testC.c(24): error C2065: 'a' : undeclared identifier
      testC.c(24): error C2100: illegal indirection
4

1 回答 1

1

如果您使用 VS2010 中的 C 编译器编译代码,则必须在函数顶部定义每个变量。

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

typedef double Td;

int main(int argc, char *argv[])
{
    FILE *fp;
    Td x;
    Td *a;
    if ( (fp=fopen("junk_out.txt","w")) == NULL )
    {
            printf("Cannot open file.\n");
            exit(1);
    }
    fprintf(fp,"%f \n",3.1420);
    fclose(fp);
    x=3.14;
    a = &x;
    printf("%f \n",a);
    printf("%f \n",x);
    printf("%f \n",*a);

    return 0;
}

在 C++ 中,您可以在任何地方定义。

于 2012-09-29T21:16:12.733 回答