rsorki
rsorki

Reputation: 1

How to make a basic C makefile?

I am trying to make a simple Makefile for a hello world program in c currently, I compile with:

gcc -Wall -std=c99 helloWorld.c

In the Makefile what I have so far is:

CC = gcc
CFLAGS = -Wall -std=c99

helloWorld.exe: helloWorld.c
    $(CC) $(CFLAGS) -o helloWorld.exe

Also, that is a tab and not spaces in the second line
When I enter either make or make --trace I get:

make: *** No targets specified and no makefile found. Stop.

Upvotes: 0

Views: 1677

Answers (1)

Read documentation of make. Beware that TAB characters are significant in Makefile-s (most other build automation systems, e.g. ninja, don't have this historical misfeature). Your question and my answer don't show these tabs but you need to be sure they are there (each code line starting here with several spaces should really start with a single tab character).

helloWorld.exe: helloWorld.c
    $(CC) $(CFLAGS) -o helloWorld.exe

is wrong. You don't pass helloWorld.c to gcc.

You want at least

 helloWorld.exe: helloWorld.c
     $(CC) $(CFLAGS) -o helloWorld.exe helloWorld.c

and you could (and actually should) use the $@ and $^ special make automatic variables. Be also aware of builtin rules (try make -p). Perhaps on your system having just helloWorld.exe: helloWorld.c without explicit actions might be enough. I recommend having the usual clean: target with the appropriate rule.

You probably want to explicitly set in your Makefile, if invoking GCC:

CFLAGS= -Wall -g

because you should ask for all warnings and debug info (since gcc won't produce them if not asked to).

To debug your Makefile: try first make -n. Then make --trace and perhaps use remake with -x.

You'll find many examples of Makefile, e.g. this.

Be sure to clean your file tree (either with a good - but still missing - clean target and then make clean, or manually by removing any object files and any executable) after each edition of Makefile.

When I enter either make or make --trace I get:
make: *** No targets specified and no makefile found.

This means that you are running that make command in the wrong directory. Before running make check with pwd or /bin/pwd your working directory. It probably is not what you believe it is. List also files in it (with ls on Linux and POSIX, with DIR on MSDOS & Windows); you should see both your Makefile and your helloWorld.c at least.

Check also that your PATH variable is correct (e.g. with echo $PATH on POSIX systems).

PS. I am surprised of the .exe suffix. On my Linux system I don't use and don't need it.

Upvotes: 2

Related Questions