Example - GCC


考慮以下三個檔案 main.c, f.h, f.c , g.h, g.c

f.h

#ifndef F_H
#define F_H
    int f(int x);
    extern int g_val;
#endif

f.c

#include "f.h"

int g_val = 30;

int f(int x)
{
    return x + g_val;
}

g.h

#ifndef G_H
#define G_H
    void g(int x);
#endif

g.c

#include "g.h"
#include "f.h"

int g(int x)
{
    return x - g_val;
}

main.c

#include <stdio.h>
#include "f.h"
#include "g.h"

int main(int argc, const char * argv[])
{
    printf("%d %d\n", f(10), g(10));

    return 0;
}

我們應該如何使用 gcc 編譯呢?

gcc -c main.c   # 產生 main.o
gcc -c f.c      # 產生 f.o
gcc -c g.c      # 產生 g.o
gcc f.o g.o main.o -o test_exec   #連結三個 obj file 產生名為 test_exec 的執行檔

gcc 的選項很多,可去 man gcc 參考。在此我們只提及本篇所講到的

gcc -c main.c 這個動作已經包含了 cpp, compile, assemble ,直接產生 main.o

我們要分解的話可以這樣 -

  • cpp : gcc -E main.c -o main.i
  • compile : gcc -S main.i (產生 main.s)
  • assemble: gcc -c main.s (產生 main.o)

通常這些編譯的動作都會撰寫 makefile 來自動化處理,此篇無介紹 makefile 如何撰寫。

results matching ""

    No results matching ""