如何使用 make 使用 sdl2 库构建项目?

How to build project with sdl2 library with 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 库没有正确加载(因此有很多链接器错误)。但是我试图让它们进入 makefile

中的 $(CFLAGS)$(LDFLAGS)

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

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

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

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


这看起来也不对:test.o: res_path.hpp sdl_error.hpp -lSDL2。删除 -lSDL2 部分。