C++ headerとcppファイルによるコンパイル

headerとcppファイルを分割してコンパイルする方法がわからなかったので備忘録として記録する。

C++にてheaderとcppファイルによるコンパイルを行うには、分割コンパイルとリンクを行う必要がある。 student.hとstudent.cppによりクラスを作成し、mainからstudentインスタンスを呼び出す事を考える。

student.h

using namespace std;

class student{
        int ID;
        //string name;

public:
        student(int id=100);

        int getID();
};

student.cpp

#include "student.h"
#include <iostream>

student::student(int id){
        ID = id;
}

int student::getID(){
        return ID;
}
#include "student.h"
#include <iostream>

using namespace std;

main.cpp

int main(){
        //student s;
        //cout << s.getID() << endl;

        student s(5);
        cout << s.getID() << endl;
        return 0;
}

二つのcppファイルをそれぞれ分割コンパイルし、オブジェクトファイルを生成し、最後にオブジェクトファイルをリンクする。

g++ -c student.cpp -o student.o
g++ -c main.cpp -o main.o 
g++ -o main main.o student.o main.o
 ```

./main を実行すると正常動作しているのがわかる。