gpt4 book ai didi

如果不包含函数列表,C++ 程序将无法编译

转载 作者:行者123 更新时间:2023-11-28 05:58:38 24 4
gpt4 key购买 nike

我有 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 的正确方法是什么。

最佳答案

您不应该使用预处理器来#include cpp 源文件(*.cpp)。

您必须链接 Graphics.cpp 或从它编译的目标文件。

试试这个:

$ g++ -Wall -o "main" "main.cpp" "Graphics.cpp" -lSDL -lSDL_image -lSDL_mixer -lSDL_ttf

关于如果不包含函数列表,C++ 程序将无法编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33704244/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com