我有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的正确方法是什么。
答案 0 :(得分:1)
您不应该使用预处理器来#include
cpp源文件(*.cpp
)。
您必须链接 Graphics.cpp
或从中编译的目标文件。
试试这个:
$ g++ -Wall -o "main" "main.cpp" "Graphics.cpp" -lSDL -lSDL_image -lSDL_mixer -lSDL_ttf