一 点睛
1 语法格式
-x language filename
2 说明
language filename都是选项x的参数,告诉gcc源代码(filename)所使用的语言为language,使用后缀名无效。这样设定后,对以后的源文件都这样处理,一致等到再次调用-x来关闭。默认情况下,gcc是根据源文件名后缀名来判断源文件语言的,比如根据.c来知道是C语言的代码,根据.cpp后缀名知道要编译的源代码是C++语言的。
为了满足个性化的需求,有些同学希望用.pig作为C源代码文件的后缀名,此时这个选项就派上用场了。
参数language可以使用下列选项
c objective-c c-header c++ cpp-output assembler assembler-with-cpp
示例
gcc -x c test.pig
不是根据test.pig判断出编译c程序,而是根据-x的参数c来决定是编译c程序。
二 实战
1 源代码
[root@localhost test]# cat test.c
#include
int main(int argc,char *argv[])
{
printf("hello, boy \n" );
return 0;
}
2 指定汇编语言来编译
[root@localhost test]# gcc -x assembler test.c
test.c: Assembler messages:
test.c:3: Error: junk `(int argc,char *argv[])' after expression
test.c:3: Error: operand size mismatch for `int'
test.c:4: Error: junk at end of line, first unrecognized character is `{'
test.c:5: Error: invalid character '(' in mnemonic
test.c:6: Error: no such instruction: `return 0'
test.c:7: Error: junk at end of line, first unrecognized character is `}'
3 说明
因为test.c不是汇编程序,-x指定用汇编方式编译,自然出错。
4 使用根据后缀判断编译方式来编译
[root@localhost test]# gcc test.c -o test
[root@localhost test]# ./test
hello, boy
5 说明
test.c说明了是C语言,所以用C编译器进行编译。
6 代码是C++代码,后缀是C代码
[root@localhost test]# cat test1.c
#include
int main(int argc,char *argv[])
{
bool b=false;
printf("hello, boy \n" );
return 0;
}
7 使用后缀判断方式编译
[root@localhost test]# gcc test1.c -o test1
test1.c: In function ‘main’:
test1.c:5:5: error: unknown type name ‘bool’
bool b=false;
^
test1.c:5:12: error: ‘false’ undeclared (first use in this function)
bool b=false;
^
test1.c:5:12: note: each undeclared identifier is reported only once for each function it appears in
8 出错分析
编译程序根据test1.c判断出是C程序,所以用C编译器编译,但代码具有C++语法,C编译器不识别,所以出错。
9 正确的编译方式有下面两种
[root@localhost test]# gcc -x c++ test1.c //根据-x指定为c++进行编译
[root@localhost test]# ll
total 80
-rwxr-xr-x. 1 root root 8512 Mar 10 10:21 a.out
-rwxr-xr-x. 1 root root 8512 Mar 10 10:13 test
-rwxr-xr-x. 1 root root 8968 Mar 10 09:41 test1
-rw-r--r--. 1 root root 129 Mar 10 10:18 test1.c
-rw-r--r--. 1 root root 204 Mar 10 09:40 test1.cpp
-rw-r--r--. 1 root root 110 Mar 10 10:17 test.c
-rw-r--r--. 1 root root 188 Mar 10 09:36 test.cpp
-rw-r--r--. 1 root root 16898 Mar 10 08:27 test.i
-rw-r--r--. 1 root root 1512 Mar 10 08:32 test.o
-rw-r--r--. 1 root root 502 Mar 10 08:27 test.s
[root@localhost test]# ./a.out
hello, boy
[root@localhost test]# cp test1.c test2.cpp
[root@localhost test]# gcc test2.cpp -o test2 //根据后缀名判断是C++进行编译
[root@localhost test]# ./test2
hello, boy