Calzone Stromboli Calzone Stromboli - 2 months ago 12
C++ Question

Makefile for SDL application only runs when the project has been built ahead of time

Alright, so this one is absolutely blowing my mind. Basically, I've got a simple makefile set up that runs g++ to build my bare-bones C++ project with SDL2. Now, when I run this makefile, it gives me a bunch of errors for "undefined reverence to 'SDL_Init'" and every function taken from SDL2 that I use in the program. However, when I copy the command from the makefile and run it from the terminal, everything is peachy. Without changing the file and running the make file again, it compiles just fine.

I am running Elementary OS Loki, g++ version 5.4.0 20160609, make version 4.1, libsdl2-dev version 2.0.4+dfsg1-2ubuntu2

Here is the make file that I am using:


CC = g++

CFLAGS = -g -Wall

ONAME = patchworkrpg

all: $(ONAME)
$(CC) $(ONAME).cpp $(LFLAGS) -o $(ONAME)


#include <stdio.h>

using namespace std;

const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;

int main(int argc, char* args[]) {
SDL_Window* window = NULL;

SDL_Surface* surface = NULL;
if(SDL_Init(SDL_INIT_VIDEO) < 0) {
cout << "SDL Failed to init\n";


I've striped out some of the extra stuff I had in there, but that's the gist of it. Like I said, the only thing that throws errors is the makefile when it's run, without the above file being compiled outside of the makefile with an identical command.

EDIT: Extra info

Errors when running the makefile:

g++ patchworkrpg.cpp -o patchworkrpg
/tmp/cctyEbxS.o: In function `main':
patchworkrpg.cpp:(.text+0x25): undefined reference to `SDL_Init'
patchworkrpg.cpp:(.text+0x62): undefined reference to `SDL_CreateWindow'
patchworkrpg.cpp:(.text+0x8a): undefined reference to `SDL_GetWindowSurface'
patchworkrpg.cpp:(.text+0x98): undefined reference to `SDL_Delay'
collect2: error: ld returned 1 exit status
<builtin>: recipe for target 'patchworkrpg' failed
make: *** [patchworkrpg] Error 1

Command typed into the terminal that works just fine:

g++ patchworkrpg.cpp -lSDL2 -o patchworkrpg

I've also tried running that exact command from the makefile and it's failed with the exact same errors

mkj mkj

(Your example Makefile and source file were incomplete, so I had to edit them to test this.)

In your Makefile:

ONAME = patchworkrpg

all: $(ONAME)
    $(CC) $(ONAME).cpp $(LFLAGS) -o $(ONAME)

all depends on patchworkrpg, but there is no rule to make patchworkrpg, so make creates the implicit rule g++ patchworkrpg.cpp -o patchworkrpg you see on the fly.

Not quite sure how you try to organize things, but to actually run your own command line this change should fix it:

all: $(ONAME).cpp