Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiling SFML on linux (ubuntu)

In compiling a SFML app,

  • I need to first create the cpp file with the SFML code and save file
  • Then write the command: g++ -c main.cpp to compile and create the object file.
  • Finally, to create SFML app, i need to write the command:
    g++ main.o -o sfml-app -lsfml-graphics -lsfml-window -lsfml-system

I was successfully able to compile and run my first app, but can't we shorten this process, I mean do I have to type out this every time I compile, and make application?

I have this question also about compiling c++ files in general. Every time I have to write g++ filename.cpp -o filename. How can I shorten this process? Thank you.

like image 268
jonsno Avatar asked Jul 23 '26 13:07

jonsno


2 Answers

It is very common to use a Makefile on Linux. The Makefile is simpler if you name your main source file the same as you want your finished program to be called.

So if you rename your main.cpp file to sfml-app.cpp and then create a file called Makefile and copy this text into it:

# optional flags (if the compiler supports it)
CXXFLAGS += -std=c++11

# HIGHLY RECOMMENDED flags
CXXFLAGS += -Wall -Wextra -pedantic-errors

# required for SFML programs
LDLIBS := $(shell pkg-config sfml-all --libs)

# The rest will turn any source file ending in .cpp
# into a program of the same name

SOURCES := $(wildcard *.cpp)
PROGRAMS := $(patsubst %.cpp,%,$(SOURCES))

all: $(PROGRAMS)

clean:
    $(RM) $(PROGRAMS)

Type: make to build the programs and make clean to remove them.

Note: The indentation of the $(RM) $(PROGRAMS) command must be a TAB, not spaces.

If you want to compile another program in the same directory simply create another source file in the directory another-app.cpp and make will automatically turn it into a program.

This Makefile will turn any source file (ending in .cpp) into a program of the same name.

Note: When you want to build larger, multi-file programs you will need a different Makefile. If you are serious about programming then you should learn make.

Here you can learn all about make.

like image 199
Galik Avatar answered Jul 25 '26 06:07

Galik


You can write a .sh script that executes the commands:

g++ -c main.cpp
g++ main.o -o sfml-app -lsfml-graphics -lsfml-window -lsfml-system
like image 45
Np3w Avatar answered Jul 25 '26 04:07

Np3w



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!