我正在尝试使用cl.exe(64位命令行)在VS2010 Professional中编译C程序。在VS2010或VS2008中遇到奇怪的错误。相同的代码编译&在没有问题的GNU gcc中运行(Cygwin)。有任何想法吗?在我理解这里的问题之前,不能继续使用真实的东西。谢谢!
filename: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
答案 0 :(得分: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 ++中,您可以定义所需的任何位置。