linux C下多檔案編譯,以及Makefile的使用

來源:互聯網
上載者:User

標籤:

由於在C語言中,不能把所有的代碼都放在一個.c檔案裡面,這樣這個.c檔案會很大,而且代碼維護起來會很麻煩。

於是在網上找了些C語言多檔案編程的樣本,記錄下我的學習過程。

 

我們可以把我們的代碼按功能進行劃分,一些源檔案存放函數的實現,一些標頭檔聲明這些函數,這樣代碼會更有條理。

標頭檔的大致格式:

#ifndef _ABC_H_#define _ABC_H_//以上代碼是為了防止這個標頭檔被多次包含,確保名字唯一//宏定義#define _MAX 100//結果體聲明typedef struct{int a;}ABC;//函式宣告void abcfun(void);...#endif

  

接下來介紹下多檔案編程的小例子

功能:在main.c裡面調用其他兩個源檔案裡面的函數,然後輸出字串。

 

1、main.c

#include"mytool1.h"#include"mytool2.h"int main(int argc,char** argv){           mytool1_printf("hello.");           mytool2_print("hello");           return 1;}

2、 mytool1.h     mytool1.c

//mytool1.h#ifndef _MYTOOL_1_H#define _MYTOOL_2_Hvoid mytool1_printf(char* print_str);#endif//mytool1.c#include"mytool1.h"#include<stdio.h>void mytool1_printf(char* print_str){         printf("This is mytool1 print %s\n",print_str);}

3、 mytool2.h mytool2.c

//mytool2.h#ifndef _MYTOOL_2_H#define _MYTOOL_2_hvoid mytool2_print(char* print_str);#endif//mytool2.c#include "mytool2.h"

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

 

在linux下,把這幾個檔案放在同一個目錄下,然後在shell中輸入

 

gcc -c main.cgcc -c mytool1.cgcc -c mytool2.cgcc -o main main.o mytool1.o mytool2.o

  就可以產生可執行檔 main

 

 

 

關於 Makefile 還沒學清楚,學清楚了補充。

引用:

http://blog.163.com/m13591120447_1/blog/static/21637918920132365724538/

http://soft.chinabyte.com/os/12/11584512.shtml

linux C下多檔案編譯,以及Makefile的使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.