創建頭文件聲明返回 void/char/int/float 且帶參數的函數。實現文件定義函數體(輸出函數名/參數/返回類型)。主文件調用所有函數。
#ifndef TEST1_H #define TEST1_H #includeusing namespace std; void fun1(int); char fun2(); int fun3(float); float fun4(char); #endif
#include "test1.h" #includeusing namespace std; void fun1(int a) { cout << "fun1(int " << a << ") returns void\n"; } char fun2() { cout << "fun2() returns char\n"; return 'c'; } int fun3(float f) { cout << "fun3(float " << f << ") returns int\n"; return 0; } float fun4(char c) { cout << "fun4(char '" << c << "') returns float\n"; return 0.0f; }
#include "test1.h" #includeusing namespace std; int main() { fun1(10); fun2(); fun3(3.14f); fun4('x'); return 0; }
g++ main.cpp test1.cpp -o test
#ifndef/#define/#endif)。C++ 多文件項目結構基礎練習:頭文件聲明、源文件實現、主程序調用、編譯鏈接流程。為大型項目工程化打下基礎。