我在寫一個C++的練習,大體結構是在.h檔案中定義了幾個類的結構,然后分cpp檔案實作,每個類一個cpp檔案。
編譯的時候單個cpp檔案都編譯過去了。
但是最后鏈接的時候出現錯誤
/usr/bin/ld: ./debug/run.o: in function `rpf::RP_Graphics::RP_Graphics()':
graphics.cpp:(.text+0x0): multiple definition of `rpf::RP_Graphics::RP_Graphics()'; ./debug/graphics.o:graphics.cpp:(.text+0x0): first defined here
基本都是RP_Graphics類報錯,每個函式都提示這個
請問這個是什么原因引起的?
是我.h和cpp檔案的結構用的不對嗎?
uj5u.com熱心網友回復:
namespace rpf
{
class RP_Graphics
{
private:
RP_Brush brush; // 畫筆樣式
RP_Canvas* canvas; // 操作的畫布
public:
RP_Graphics();
RP_Graphics(RP_Canvas* canvas);
~RP_Graphics();
RP_Brush& getBrush(); // 獲得畫筆,獲得后可直接修改
RP_Graphics drawPoint(const RP_Point& point) const; // 畫點
RP_Graphics drawLine(const int size ,const RP_Point** point) const; // 劃線
RP_Graphics drawRect(const RP_Rectangle& rect) const; // 繪制矩形
RP_Graphics fillRect(const RP_Rectangle& rect) const; // 繪制填充矩形
RP_Graphics drawCircle(const RP_Rectangle& rect) const; // 繪制圓形
RP_Graphics fillCircle(const RP_Point& point , const uint32_t radius) const; // 繪制圓形
RP_Graphics drawPolygon(const int size ,const RP_Point** point) const; // 繪制多邊形
RP_Graphics fillPolygon(const int size ,const RP_Point** point) const; // 繪制多邊形
// 繪制Canvas和Image的函式
RP_Graphics draw(RP_Canvas& canvas , const RP_Point& rect) const;
RP_Graphics draw(RP_Canvas& canvas , const RP_Rectangle& rect) const;
RP_Graphics draw(RP_Canvas& canvas , const RP_Rectangle& r_rect,const RP_Point& rect) const;
RP_Graphics draw(RP_Canvas& canvas , const RP_Rectangle& r_rect,const RP_Rectangle& d_rect) const;
};
}
這是.h檔案中關于RP_Graphics的定義
uj5u.com熱心網友回復:
.h檔案因為會被多處參考,因而它有義務阻止自己多次發揮作用(重復定義)。參考一下系統的.h
多半都有
#ifndef _xx_h_
#define _xx_h_
define something yourself
#endif
這種結構。
模仿之。
uj5u.com熱心網友回復:
這個做了我發現如果使用g++直接編譯的時候沒問題,只要單開編譯再連接就出問題
g++ -Isrc/include -std=c++11 -lstdc++ src/run.cpp src/graphics.cpp src/canvas.cpp src/image.cpp src/game.cpp -o main
這種方式直接過
但是我用Makefile
先把.cpp編譯成.o檔案,用g++ -c
然后使用
g++連接
這樣做肯定出問題
我把所有的類宣告都寫在一個.h檔案中了
uj5u.com熱心網友回復:
你把那些函式的實作也寫在頭檔案里了?轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/251088.html
標籤:新手樂園
上一篇:求大佬講解
下一篇:qt中智能指標的疑惑
