2012年6月12日 星期二

多檔案組成程式(C/C++)

EXAMPLE:

FILE Main.c

//include 系統內建函數
#include <plib.h>  
#include <stdio.h>
//include 自建函數
#include "UART.h" 
#include "Parameter.h" 
//變數宣告 其他C檔也會用到此變數
unsigned char ZigState;

int main(void); 
{
...
while(1);
}





FILE UART.c

//include 系統內建函數
#include <plib.h>
#include <stdio.h>
//include 自建函數
#include "UART.h"
#include "Parameter.h"

//寫在其他c檔的函式
void Init_UART1(void)
{...}
unsigned char UART2_Send(int Size,unsigned char *Data)
{...return xxx;}
unsigned char Init_Zigbee(unsigned char channel, unsigned char power)
{....return xxx; }
unsigned char Zigbee_check(unsigned char *ZigbeeData)
{...return xxx; }

FILE Parameter.h

//此檔主要用來宣告或定義常用的常數與變數,為了避免重複定義要使用#ifndef指令
//一般歸屬於其他.c檔的變數或常數盡量別混著在同一個.h檔,分開來定義,比較不會亂
#ifndef PARAMETER_H
#define PARAMETER_H
//Load 此.h檔 都可使用這些定義的變數
#define ZigbeeRst LATAbits.LATA2 
#define ZigbeeOff (0)
#define ZigbeeOn (1)
//利用extern 讓程式知道此變數是由外部宣告交由內部使用
extern unsigned char ZigState; 
#define SWAP(x,y) {int t; t = x; x = y; y = t;}
#endif

FILE UART.h

//函式宣告在.h檔內,幫助compiler尋找宣告的函式
void Init_UART1(void); 
unsigned char Init_Zigbee(unsigned char, unsigned char);
unsigned char Zigbee_check(unsigned char *);


#include: 將include的檔案資料內容完整的貼在目前的位置取代原先的 include 位置。
用法:
#include <檔案名稱.附檔名> 系統到預設的 include 目錄中尋找此檔案,
#include "檔案名稱.附檔名" 系統到當下目錄中尋找此檔案,
#include “./AAA/Test.h” 到下一層的目錄 AAA 去找 Test.h 檔
#include “../BBB/Test .h” 到上一層的目錄 BBB 去找 Test.h 檔

標頭檔:
.h(標頭檔)主要的目的就是將內建好的函式、常數以及宣告等匯入,使程式設計的過程中不用再去寫底層的程式,一般自行建立的.c檔會搭配自己的.h檔。 

避免重複宣告:
這樣的用法一般會寫在header file 當中,目的是為了避免重覆include
同一個header file compiler 會發出重覆宣告的錯誤
#ifndef _STDLIB_H_ (如果沒有定義_STDLIB_H_ 則下面的code 會被展開直到 #endif)
#define _STDLIB_H_ // 定義 _STDLIB_H_
... code
#endif // (結束 前置處理器的if 判斷 區段)

外部使用變數:
當程式會使用到外部變數時,除了原始程式的宣告,也必須在當下的程式或者load近來的.h檔宣告 "extern 資料型態 變數名稱; ",告訴compiler要使用此外部程式的變數,變數名稱宣告內容都必須一樣。



參考:
多檔案組成的程式
Header 檔的使用介紹
認識標頭檔





1 則留言:

  1. Casino City, NJ | Mapyro
    A 제천 출장샵 map showing Casino City, NJ casinos 여주 출장샵 and other gaming facilities 하남 출장안마 located in Atlantic City, 제주도 출장안마 Gaming & Hotel. 97300 S. Atlantic 창원 출장샵 City, NJ 08401.

    回覆刪除