.h和.cpp文件的區別


首先,所有的代碼是都可以放在一個cpp文件里面的。這對電腦來說沒有任何區別,

但對於一個工程來說,臃腫的代碼是一場災難,非常不適合閱讀和后期維護,

所以.h和.cpp文件更多的是對程序員的編寫習慣進行規范

  

用法

1、.h文件直接#include到需要的.cpp文件里,就相當於把.h文件的代碼拷貝到.cpp文件

2、.cpp文件需要先自己生成.o文件,把不同.o文件連接生成可執行文件。

      比如有3個cpp文件:a.cpp、b.cpp、c.cpp,其中一個包含main()函數,需要生成test程序,

      步驟:

      1、生成3個.o文件:cc -c a.cpp

                                   cc -c b.cpp

                                   cc -c c.cpp

            這樣就得到3個.o文件:a.o、b.o、c.o

      2、鏈接生成test程序:cc -o test a.o b.o c.o

           就得到test可執行程序,輸入./test就可執行程序了。

規范

1、h文件一般包含類聲明;

2、cpp文件一般為同名h文件定義所聲明的類函數

說明:一般可在cpp文件直接添加main()就可以測試該模塊功能。

例(g++):

1 //point.h
2 #include<stdio.h>
3 typedef struct Point Point;
4 struct Point{
5     int x,y;
6     Point(int _x,int _y);
7     void ADD(Point _p);
8     void Print();
9 };
 1 //point.c
 2 #include"point.h"
 3 #define DEBUG 1
 4 Point::Point(int _x,int _y){
 5     x=_x;
 6     y=_y;
 7 }
 8 void Point::ADD(Point _p){
 9     x+=_p.x;
10     y+=_p.y;
11   
12 ▽oid Point::Print(){
13     printf("(%d,%d)\n",x,y);
14 }
15 
16 #if DEBUG
17 int main(){
18     Point a(1,1);
19     Point b(2,2);
20     a.Print();
21     a.ADD(b);
22     a.Print();
23     return 0;
24 }
25 #endif

執行:

g++ -c point.c
g++ -o test point.o

獲得可執行程序test

執行test,可得到結果:

[zjp@virtual-CentOS-for-test workstation]$ ./test
(1,1)
(3,3)

 


免責聲明!

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



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