Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

คอมไพล์หลายไฟล์ .cpp ใน C++

คอมไพล์หลายไฟล์ .cpp พร้อมกันด้วย g++ โดยระบุชื่อไฟล์ต่อกัน

คำสั่ง

g++ file1.cpp file2.cpp file3.cpp -o myprogram
./myprogram

ตัวอย่าง: แยกฟังก์ชัน area() ไปไฟล์ area.cpp

// area.cpp
float area(float r) { return 3.1415 * r * r; }
float area(float l, float w) { return l * w; }

// find_area.cpp
#include <iostream>
#include "area.cpp" // หรือ compile แยก: g++ area.cpp find_area.cpp
using namespace std;
int main() {
    cout << area(2.5) << endl;
    cout << area(5, 7) << endl;
}

แนวทางปฏิบัติที่ดี (Best Practice)

  1. สร้าง header file area.h ประกาศ prototype
  2. #include "area.h" ใน find_area.cpp
  3. คอมไพล์: g++ area.cpp find_area.cpp -o find_area

การ include .cpp โดยตรงไม่แนะนำสำหรับโปรเจคใหญ่ ควรแยก header และ compile/link แยก