一、說明
eclipse作為強大的開源開發平台,加入CDT插件後能實作在eclipse平台進行C/C++項目開發。網上目前搜到的C++項目示例一般都是簡單的HelloWorld,其忽略了自定義的頭檔案的使用,由此讀者後續要自定義頭檔案時會遇到困難,本文則用簡單的帶自定義的頭檔案的C++項目為例進行示範。
二、建立項目
1. File -> New -> C/C++ Project -> Project name -> Finish
完成後得到一個空的C++項目,如下圖:
2. 右擊項目名 -> New -> Folder 建立header檔案夾放頭檔案,src檔案夾放源檔案(可以自己定義)
得到項目檔案結構圖:
3. 在header、src檔案夾分别添加頭檔案和源檔案
3.1 header右擊 -> New -> Header File
頭檔案代碼:
/*
* person.h
*
* Created on: 2018年8月27日
* Author: ywq
*/
#ifndef HEADER_PERSON_H_
#define HEADER_PERSON_H_
#include <string>
using std::string;
class person{
public:
person(const string& n="",int a=0,double w=0.0); //構造函數
void show () const; //成員函數
private:
string name;
int age;
double weight;
};
#endif /* HEADER_PERSON_H_ */
3.2 src 右擊 -> New -> Source File ,建立兩個cpp源檔案(person.cpp 和 main.cpp)
person.cpp代碼:
/*
* person.cpp
*
* Created on: 2018年8月27日
* Author: ywq
*/
#include <iostream>
#include "person.h"
person::person(const string& n,int a,double w):name(n),age(a),weight(w){}
void person::show () const{
std::cout<<"name: "<<name<<" age: "<<age<<" weight: "<<weight<<std::endl;
}
main.cpp代碼:
/*
* main.cpp
*
* Created on: 2018年8月27日
* Author: ywq
*/
#include <iostream>
#include "person.h"
int main(){
person a("Jack",18,60.1);
a.show();
return 0;
}
最終項目檔案結構如下:
4. 編譯:Project -> Build Project
這時候會出現錯誤:
解決辦法:
添加頭檔案(Includes)路徑:右擊項目名 -> Properties -> C/C++ General -> Paths and Symbols -> GNU C++ -> Add...
Workspace -> header -> OK -> OK -> Apply and Close
此時再build,可以完成。
5. Run -> Run Configurations -> C/C++ Applications 右擊 -> New -> test Debug -> 右下角Run
即可執行程式,控制台顯示如下:
三、進階選項
經過過程二的項目都可以直接由
來編譯和運作(最左邊錘子為build, 右邊綠色播放按鈕為run,紅色按鈕為stop)。
再右邊Run可以選擇Run/Debug模式,最右邊為launch,可以點選右邊設定進入configuration選擇Project和C/C++ Application.