简体   繁体   中英

How to build project with sdl2 library with make?

I am reading https://www.willusher.io/pages/sdl2/ , I in the first chapter, I got this file tree:

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

Now from the Lessons directory, I would like to build the test.cpp file:

#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;
}

But I do not know, how to include the sdl2 dependencies. Here the makefile looks like this:

#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

When run with make command, the output is:

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

Now I see the makefile gets the source file src/test.cpp correctly, but the sdl2 library were not properly loaded (and thus those many linker errors). But I tried to get them in $(CFLAGS) and $(LDFLAGS) in the makefile

-lSDL2 needs to come after test.o in the command.

According to the make manual , the implicit rule you're using looks like this:

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

Meaning your linker flags have to go to LDLIBS rather than LDFLAGS .


Also this looks wrong: test.o: res_path.hpp sdl_error.hpp -lSDL2 . Remove the -lSDL2 part.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM