C語言頭文件源文件


C語言頭文件源文件

1、頭文件與源文件

頭文件用於聲明接口函數,格式如下

如創建test.h

#ifndef _TEST_H_
#define _TEST_H_

/*接口函數的申明*/

#endif
#ifndef _TEST_H_
#define _TEST_H

int sum(int x, int y);

void swap(int *x, int *y);

int max(int x, int y);

#endif

 

源文件用於接口函數的實現,源文件中只寫接口函數的實現不能寫main()函數

#include <stdio.h>
#include "test.h"

int sum(int x, int y)
{
    return x+y;
}

void swap(int *x, int *y)
{
    int tmp;
    tmp = *x;
    *x = *y;
    *y = tmp;
}

int max(int x, int y)
{
    return (x>y)? x : y;
}

 

2、用戶文件

頭文件和源文件一般是標准庫文件或者自定義的庫文件,用戶文件則是我們自己寫的文件,我們需要在用戶文件中使用庫文件或函數,就要包含所需的頭文件

#include <stdio.h>
#include "test.h"

int main()
{
    int a = 1, b = 2;

    swap(&a, &b);

    printf("sum(%d,%d)=%d\n", a, b, sum(a, b));
    printf("a=%d, b=%d\n", a, b);
    printf("max(%d,%d)=%d\n", a, b, max(a, b));

    return 0;
}

 

3、多文件編譯

當我們使用的時候,如果只編譯main.c(gcc main.c)就會報錯

 

 

 原因是在test.h中找不到函數的實現,所以在編譯時要將源文件test.c和main.c一起編譯(gcc main.c test.c),這樣就不會報錯

 

4、makefile和shell腳本

當我們包含的頭文件特別多,在編譯時就要編譯很多源文件(gcc main.c test1.c test2.c test3.c test4.c ... testn.c) ,這樣就會非常長,所以我們可以將命令行寫到腳本里面進行批處理

(1)shell腳本

創建一個build.sh的腳本文件,然后將需要編譯的命令行寫到腳本文件里,編譯時輸入命令 sh build.sh就完成了編譯

 

 

 

 

(2)makefile

 

(待續。。。)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM