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

ใช้ G++ คอมไพล์หลายไฟล์ .cpp และ .h

คอมไพล์หลายไฟล์พร้อมกันด้วย g++ รวม .h และ .cpp ได้ (แต่ .h ปกติไม่ compile ตรง)

คำสั่ง

g++ area.h find_area.cpp -o find_area
# หรือ
g++ area.cpp find_area.cpp -o find_area

ตัวอย่าง

// area.h
float area(float r);
float area(float l, float w);

// 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.h"
using namespace std;
int main() {
    cout << area(2.5) << endl;
    cout << area(5, 7) << endl;
}

Best Practice

  • Header (.h) มีแค่ declarations
  • Implementation (.cpp) มี definitions
  • Compile ทุก .cpp พร้อมกัน หรือ compile เป็น object files แล้ว link
  • g++ -c area.cpp -o area.o แล้ว g++ area.o find_area.cpp -o find_area