首页 > 解决方案 > 如何使用 sdl2 库和 make 构建项目?

问题描述

我正在阅读https://www.willusher.io/pages/sdl2/,我在第一章中,我得到了这个文件树:

Lessons
├── bin
├── include
│   ├── res_path.hpp
│   └── sdl_error.hpp
├── Lesson1
│   └── src
│       ├── hello_world.cpp
│       └── test.cpp
├── makefile
└── res
    └── Lesson1
        └── hello.bmp

现在从Lessons目录中,我想构建test.cpp文件:

#include <iostream>
#include <SDL2/SDL.h>
#include <string>
#include "res_path.hpp"
#include "sdl_error.hpp"

int main()
{
    if (SDL_Init(SDL_INIT_EVERYTHING) != 0)
        print_err("sdl_init");

    std::cout << "Resource path is: " << getResourcePath() << std::endl;

    SDL_Quit();
    return 0;
}

但我不知道,如何包含sdl2依赖项。这里的makefile看起来像这样:

#project variables
CC = g++
CPPFLAGS = -I include
VPATH = include $(wildcard Lesson[0-9]/src)

#SDL2 vairables
CFLAGS = $(shell sdl2-config --cflags)
LDFLAGS = $(shell sdl2-config --libs)


test: test.o
test.o: res_path.hpp sdl_error.hpp -lSDL2

使用make命令运行时,输出为:

g++  -I include  -c -o test.o Lesson1/src/test.cpp
g++ -lSDL2  test.o   -o test
/usr/bin/ld: test.o: in function `getResourcePath(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)':
test.cpp:(.text+0xa5): undefined reference to `SDL_GetBasePath'
/usr/bin/ld: test.cpp:(.text+0xdb): undefined reference to `SDL_free'
/usr/bin/ld: test.cpp:(.text+0xf8): undefined reference to `SDL_GetError'
/usr/bin/ld: test.o: in function `print_err(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)':
test.cpp:(.text+0x2f8): undefined reference to `SDL_GetError'
/usr/bin/ld: test.o: in function `main':
test.cpp:(.text+0x346): undefined reference to `SDL_Init'
/usr/bin/ld: test.cpp:(.text+0x42f): undefined reference to `SDL_Quit'
collect2: error: ld returned 1 exit status
make: *** [<builtin>: test] Error 1

现在我看到 makefile 正确地获取了源文件src/test.cpp,但是sdl2库没有正确加载(因此有很多链接器错误)。$(CFLAGS)但我试图让它们进入$(LDFLAGS)makefile

标签: c++makefilebuildsdl-2

解决方案


-lSDL2需要test.o在命令之后。

根据make manual,您使用的隐式规则如下所示:

$(CC) $(LDFLAGS) n.o $(LOADLIBES) $(LDLIBS)

这意味着您的链接器标志必须转到LDLIBS而不是LDFLAGS.


这看起来也不对:test.o: res_path.hpp sdl_error.hpp -lSDL2. 拆下-lSDL2零件。


推荐阅读