【发布时间】:2016-02-15 17:07:32
【问题描述】:
我有 3 个文件,main.cpp、Graphics.cpp 和 Graphics.h。函数定义在 Graphics.h 中。这些函数在 Graphics.cpp 中。主程序在 main.cpp 中。代码编译正常,但不会编译。
当我跑步时
$ g++ -Wall -o "main" "main.cpp" -lSDL -lSDL_image -lSDL_mixer -lSDL_ttf
/tmp/cce3Gqez.o: In function `main':
main.cpp:(.text+0xfd): undefined reference to `Graphics::clear(int, int, int)'
main.cpp:(.text+0x207): undefined reference to `Graphics::drawPixel(int, int, int, int, int)'
main.cpp:(.text+0x364): undefined reference to `Graphics::drawRect(int, int, int, int, int, int, int)'
main.cpp:(.text+0x4b7): undefined reference to `Graphics::fillRect(int, int, int, int, int, int, int)'
main.cpp:(.text+0x4c5): undefined reference to `Graphics::flip()'
/tmp/cce3Gqez.o: In function `InitProgram()':
main.cpp:(.text+0x54f): undefined reference to `Graphics::init(int, int, bool)'
collect2: error: ld returned 1 exit status
无法识别对函数的引用? 当我在 main.cpp 的顶部包含“#include”Graphics.cpp“”时,程序运行正常。我确信这样做是不合适的,但我不能让它以任何其他方式工作。 这是 3 个源文件:
#include "Graphics.h"
//#include "Graphics.cpp"
const int FPS = 30;
const int FRAME_TIME = 1000/FPS;
const int SCREEN_WIDTH = 800;
const int SCREEN_HEIGHT = 600;
const int FULLSCREEN = false;
Graphics graphics;
bool InitProgram();
void FreeProgram();
bool ProgramRunning();
int main(int argc, char *argv[])
{
if(!InitProgram())
{
FreeProgram();
return false;
}
int counter = 0;
while(ProgramRunning())
{
int frameStart = SDL_GetTicks();
counter++;
if(counter > 90)
{
counter = 0;
graphics.clear(rand()%255, rand()%255, rand()%255);
}
for(int i = 0; i < 100; i++)
graphics.drawPixel(rand()%SCREEN_WIDTH, rand()%SCREEN_HEIGHT, rand()%255, rand()%255, rand()%255);
graphics.drawRect(rand()%SCREEN_WIDTH, rand()%SCREEN_HEIGHT, rand()%100, rand()%100, rand()%255, rand()%255, rand()%255);
graphics.fillRect(rand()%SCREEN_WIDTH, rand()%SCREEN_HEIGHT, rand()%100, rand()%100, rand()%255, rand()%255, rand()%255);
graphics.flip();
int frameTime = SDL_GetTicks()-frameStart;
int delay = FRAME_TIME - frameTime;
if(delay > 0)
SDL_Delay(delay);
}
FreeProgram();
return 0;
}
bool InitProgram()
{
if(SDL_Init( SDL_INIT_EVERYTHING) == -1)
return false;
if(!graphics.init(SCREEN_WIDTH, SCREEN_HEIGHT, FULLSCREEN))
return false;
SDL_WM_SetCaption("Graphics Test", NULL);
return true;
}
void FreeProgram()
{
SDL_Quit();
}
bool ProgramRunning()
{
SDL_Event event;
while(SDL_PollEvent(&event))
{
if(event.type == SDL_QUIT)
return false;
}
return true;
}
我该怎么做才能正确编译?我是否缺少链接器标志?我正在使用 g++ 并且我是编写头文件的新手。编译 main.cpp 的正确方法是什么。
【问题讨论】:
标签: c++ class compilation header include