在 Unix 中,把 C 源程式轉成可執行檔的工具是 cc,多數系統裡它其實是一個 shell 指令檔。有些系統的 C 編譯器不叫 cc,例如 Sun 工作站常用的 gcc,但這無關緊要——用法大同小異。以下以 SVR4 的 C 編譯系統為例。
當程式碼分散在多個檔案時,只需在命令列逐一列出這些 C 檔。把 myprog.c 拆成兩個 C 檔與一個標頭檔:
/* myprog.h */
# include <stdio.h>
# include <ctype.h>
# define TESTOK 1
/* myprog.c */
#include "myprog.h"
void main (int argc, char * argv[])
{
int i;
for (i=1; i<argc; i++)
if (TestInput(argv[i]) == TESTOK)
printf("The %dth value '%s' is ok! \n", i, argv[i]);
else
printf("The %dth value '%s' is BAD! \n", i, argv[i]);
}
/* myfunc.c */
#include "myprog.h"
int TestInput(char * ValueInput)
{
while (* ValueInput)
if (!isdigit(*ValueInput)) return (! TESTOK);
else ValueInput ++;
return ((100/atoi(ValueInput))? TESTOK : ! TESTOK);
}
編譯時輸入:
$ cc -o myprog myprog.c myfunc.c
若漏掉 myfunc.c,由於 TestInput() 不是標準庫函式,連結器找不到符號定義,流程會失敗並顯示:
Undefined first referenced symbol in file TestInput myprog.o id: myprog:fatal error: Symbol referencing errors. No output written to myprog
myprog 不會產生,但 myprog.c 的目標碼已經生成了(編譯階段成功、連結階段失敗):
$ ls -l rw-r--r-- 1 yxz user 454 Sep 1 09:27 myfunc.c rw-r--r-- 1 yxz user 479 Sep 1 09:28 myprog.c rw-r--r-- 1 yxz user 298 Sep 1 09:27 myprog.h rw-r--r-- 1 yxz user 924 Sep 1 09:28 myfunc.o
既然 myfunc.o 已存在,就可以直接連結它來完成:
$ cc -o myprog myprog.o myfunc.c
這裡有個關鍵觀念:cc 命令列中的檔案參數不必全是 .c 檔,目標檔(.o)、預處理後的 .i 檔、編譯後的 .s 檔同樣可以當參數傳入。理解編譯系統的分段本質後,這一切就很自然——它只需對不同型別的檔案做對應處理即可。