歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux教程 >> Linux 下GCC的於處理器CPP使用實例

Linux 下GCC的於處理器CPP使用實例

日期:2017/2/28 16:00:34   编辑:Linux教程

[root@localhost ansi]# cpp -dM /dev/null //查看GCC內部自定義的宏

第一:通過使用宏去掉注釋

[root@localhost ansi]# vim dtest.c

#include <stdio.h>

int main(void)

{

#ifdef TEST

printf("Test mode\n");

#endif

printf("Tuning......\n");

return 0;

}

1、使用宏(拿掉#if 0 …………#end if的注釋)

[root@localhost ansi]# gcc -Wall -O -DTEST dtest.c -o dt

[root@localhost ansi]# ./dt

Test mode

Tuning......2、不使用宏

[root@localhost ansi]# gcc -Wall -O dtest.c -o wanyan

[root@localhost ansi]# ./wanyan

Tuning......

第二:通過宏實現賦值

[root@localhost ansi]# vim num.c

#include <stdio.h>

int main(void)

{

printf("Value of NUM is %d\n",NUM);

return 0;

}

1、只寫-D默認的值為1(正確)

[root@localhost ansi]# gcc -Wall -O -DNUM num.c -o num

[root@localhost ansi]# ./num

Value of NUM is 1

2、給D賦值(正確)

[root@localhost ansi]# gcc -Wall -O -DNUM=123 num.c -o wanyan

[root@localhost ansi]# ./wanyan

Value of NUM is 123

3、不寫-D(錯誤)

[root@localhost ansi]# gcc -Wall -O num.c -o ethnicitybeta

num.c: In function 'main':

num.c:5: error: 'NUM' undeclared (first use in this function)

num.c:5: error: (Each undeclared identifier is reported only once

num.c:5: error: for each function it appears in.)

第三:編譯的過程(模擬),過程.c(原始代碼部分)-->.i(預處理的部分)-->.s(匯編語言部分)-->.o(包含機器碼的部分,目標文件)-->可執行的文件

[root@localhost test]# vim bad.c

#include <stdio.h>

int main(void)

{

printf("2 plus 2 is %d\n",4);

return 0;

}

~

下邊這個步驟就是為了保存預處理的結果文件

[root@localhost test]# gcc -Wall -O -c -save-temps bad.c //重點在-save-temps的使用

[root@localhost test]# ls

bad.c bad.i bad.o bad.s

第四:GCC –E來查看過程(並不是真正的編譯)

[root@localhost test]# vim bad.c

#include <stdio.h>

int main(void)

{

printf("2 plus 2 is %d\n",4);

return 0;

}

[root@localhost test]# gcc -E bad.c

………..

…………

………..

extern void funlockfile (FILE *__stream) __attribute__ ((__nothrow__));

# 844 "/usr/include/stdio.h" 3 4

# 2 "bad.c" 2

int main(void)

{

printf("2 plus 2 is %d\n",4);

return 0;

}

實驗結束

Copyright © Linux教程網 All Rights Reserved