萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 作業系統 >  >> Linux 教學

新手教室:Linux 下 Makefile 檔案基本概念

將各模組關係寫進 Makefile 並註明編譯指令,當有模組原始碼修改後,執行 make 指令運行 Makefile 即可重新編譯涉及修改的模組,其他模組不受影響。

Makefile 寫法

目標、組件、規則

例如有 5 個檔案:

/* main.c */
#include "mytool1.h"
#include "mytool2.h"
int main(int argc,char **argv)
{
    mytool1_print("hello");
    mytool2_print("hello");
}

/* mytool1.h */
#ifndef _MYTOOL_1_H
#define _MYTOOL_1_H
void mytool1_print(char *print_str);
#endif

/* mytool1.c */
#include "mytool1.h"
void mytool1_print(char *print_str)
{
    printf("This is mytool1 print %s\n",print_str);
}

/* mytool2.h */
#ifndef _MYTOOL_2_H
#define _MYTOOL_2_H
void mytool2_print(char *print_str);
#endif

/* mytool2.c */
#include "mytool2.h"
void mytool2_print(char *print_str)
{
    printf("This is mytool2 print %s\n",print_str);
}

編譯步驟:

gcc -c main.c (生成 main.o)
gcc -c mytool1.c (生成 mytool1.o)
gcc -c mytool2.c (生成 mytool2.o)
gcc -o main main.o mytool1.o mytool2.o (生成 main)

對應 Makefile 寫法:

main: main.o mytool1.o mytool2.o
    gcc -o $@ $^
main.o: main.c mytool1.h mytool2.h
    gcc -c $<
mytool1.o: mytool1.c mytool1.h
    gcc -c $<
mytool2.o: mytool2.c mytool2.h
    gcc -c $<

透過 make 指令即可執行編譯。

Linux 上有許多函式庫,C 語言編寫的各類庫總稱 libc,glibc 為 libc 子集,由 GNU 提供。核心提供的系統函數與系統呼叫不包含在 libc 中。Linux 系統預設安裝 glibc,常用庫 gcc 會自動尋找無需理會。/lib、/usr/lib、/usr/local/lib 有標準庫,只需 -l+庫名 不用指定路徑。其他庫必須在 gcc 時用 -L+具體路徑。

copyright © 萬盛學電腦網 all rights reserved