# C++ hpp and cpp 1. reference: https://www.youtube.com/watch?v=RMnpwICsgYo 3. **.hpp是一個interface,而.cpp是implement** 4. 假如今天我們想要建立一個library或是把function分開 * ``include "lib" ``` * ```include``` 就是把所指到file copy到此file中 * "lib"則是所指到file位置;< lib >則是會從系統位置($PATH)中去找library,例如:std 1. 直接在func.cpp宣告同時定義implement 1. 在main.cpp中```include "func.cpp"``` * 則compiler會把include中所指到func.cpp的內容複製到main.cpp中,現在main就含有main加上func內容 2. 使用```g++ -c main.cpp -o main``` * compiler把main+func當成一個檔案然後compile成一個object;如果有加-o則直接可以產生一個執行檔 * 缺點(一): 如果今天code超級多,但我們只改變其中一個file,那不管其他file有沒有更動全部都要重新compile,這很浪費時 * 缺點(二): 如果library(func.cpp)中的implement具有商業性或是想要保密,我們就很難讓這個library(func.cpp)被其他人使用 2. func.cpp搭配func.hpp使用 * 首先我們會有三個檔案,func.cpp, func.hpp和main.cpp * 內容: 1. **func.cpp**(implement) ``` include "func.hpp" // function implement in add(int a, int b){ return a+b; } ``` * include首先把func.hpp中的function decleration複製到func.cpp中,同時告訴compile以下implement是依照func.hpp中的interface執行 2. **func.hpp**(interface) ``` #ifndef YOUFUNC_HPP #define YOUFUNC_HPP int add(int a, int b); #endif ``` * hpp file中只宣告function, custom data type, class,但是不寫implement * #ifndef YOUFUNC_HPP/#define YOUFUNC_HPP/#endif,加上這個主要是前面有提到```include```實際上就是一個copy,假如今天有好幾個file想要用到此library中的function,他們都會```include "library.hpp"```,此會造成其中定義的function被複製並重新宣告好幾次,因此加入此來預防 3. **main.cpp** ``` include <iostream> include "func.hpp" int main(){ std::cout << add(1,2) <<std::endl; return 0; } ``` * 在主要file中,我們只需要把宣告library(func.hpp)的file include進來就好,而在compile時linker會依據此去幫我們找到對應的binary code連成excutable file * 通常都是include .hpp不會用.cpp !!! * compile: 1. 把main以及library分別compile成object file(還沒有link不完整無法執行的binary code) * ```g++ -c main.cpp func.cpp``` or ```g++ -c main.cpp; g++ -c func.cpp``` * compile後會得到main.o和func.o 2. 把所有object file全部link成executable file * ```g++ main.o func.o -o exefile``` * 補充: 上面兩階段也可以直接修改成```g++ -c main.cpp func.cpp -o exefile``` * 好處(一): 由於main和func是先分別compile成object file在link成一起,因此我們在修改其中一個檔案時可以只重新compile其中修改的file成object就好,然後在link,而不用整個所有都重新compile * 好處(二): library就可以紙包成一個binary的object file,如此可以防止implement外洩,但同時又可以透過.hpp這個interface讓要使用此library的使用者知道有哪些function並怎麼用