เราจะมาดูวิธีการคอมไพล์ไฟล์ cpp หลายไฟล์ในโปรแกรม C++ งานนี้ง่ายมาก เราสามารถระบุชื่อเป็นรายการให้กับคอมไพเลอร์ g++ เพื่อคอมไพล์ให้เป็นไฟล์ปฏิบัติการไฟล์เดียว
ในการรวบรวมหลายไฟล์ เช่น abc.cpp และ xyz.cpp พร้อมกัน ไวยากรณ์จะเป็นดังนี้ -
g++ abc.cpp xyz.cpp
ในการรันโปรแกรม เราสามารถใช้สิ่งนี้ −
./a.out
ตัวอย่าง
float area(float r){
return (3.1415*r*r); //area of a circle
}
float area(float l, float w) {
return (l * w); //area of a rectangle
} ตัวอย่าง
#include <iostream>
#include "area.cpp"
using namespace std;
main() {
cout << "Area of circle with radius 2.5 is: " << area(2.5) << endl;
cout << "Area of rectangle with length and width are 5 and 7 is: " << area(5, 7) << endl;
} ผลลัพธ์
$ g++ area.cpp find_area.cpp $ ./a.out Area of circle with radius 2.5 is: 19.6344 Area of rectangle with length and width are 5 and 7 is: 35 $