How do I make a simple makefile for gcc on Linux?


For example this simple Makefile should be sufficient:


all: program
program: program.o
program.o: program.c program.h headers.h

    rm -f program program.o
run: program

Note there must be <tab> on the next line after clean and run, not spaces.

UPDATE Comments below applied


I have three files: program.c, program.h and headers.h.

program.c includes program.h and headers.h.

I need to compile this on Linux using gcc compiler. I'm not sure how to do this. Netbeans created one for me, but it's empty.

How to make a makefile?

This one looks OK, but remember to replace all indentations with Tabs:

.PHONY: all clean
CFLAGS:=$(CFLAGS) -std=c11 -Wall
objStringListDemo=$(OBJ)/LinkedListAPI.o $(OBJ)/StringListDemo.o
objStructListDemo=$(OBJ)/LinkedListAPI.o $(OBJ)/StructListDemo.o

all: StringListDemo StructListDemo

StringListDemo: $(objStringListDemo) $(INCLUDE)/LinkedListAPI.h
    ${CC} -o $< $@

StructListDemo: $(objStructListDemo) $(INCLUDE)/LinkedListAPI.h
    ${CC} -o $< $@

%.o: %.c
    ${CC} $(CFLAGS) $< -o $@

    rm -rf $(objStringListDemo) $(objStructListDemo) StringListDemo StructListDemo

Here is a very basic example of a Makefile using pkg-config, which you should really use with glib anyway, takes a lot of the pain away:

CXXFLAGS += $(shell pkg-config --cflags glib-2.0) $(shell pkg-config --cflags json-glib-1.0)
LIBS     += $(shell pkg-config --libs glib-2.0) $(shell pkg-config --libs json-glib-1.0)

all: main

main: main.o
    $(CXX) $(CXXFLAGS) main.o -o main $(LIBS)

    rm -f main main.o

Might be wise to find yourself a gnu make tutorial, so that you can better understand this example.

Now instead of running your manually typed shell command, you can just do 'make'.

Add include paths and shared library for g++ permanently

The best, most flexible way to do this is via a build system, using Make or CMake or something similar. But there is a serious learning curve. It may be simpler for right now to just create a script file to run the same commands that you have successfully used from the command line.

I assume you are using the bash shell. You can just edit a file -- call it "compile.bash". At the first line of the file, type "#!/bin/bash". That tells the system to interpret this file as a bash script file. Then on one or more subsequent lines, type the commands you just provided in you question, exactly as you use them previously. Save the file. Then run this command from the command line: "chmod +x compile.bash" (without the quotes). Make sure that the new file is located in the directory that you compile from, and you can just type: "compile.bash" instead of the long command line you were using before.

Example file "compile.bash"

g++ -o main main.cpp -I/usr/include/glib-2.0 -I/usr/include/json-glib-1.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include/ -L/usr/lib/x86_64-linux-gnu -ljson-glib-1.0 -lglib-2.0