Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compile a C program with make on Mac OS X Terminal

I recently bought a MacBook Pro and I wanted to do some coding in C with the terminal.

I'm able to compile the code with this command:

gcc filename.c –o filename

But I want to compile it with the make command, because I know it is best practice and I want to follow best practice.

make filename cc filename.c -o filename

This command is giving me the following output:

make: Nothing to be done for `ex01'.
make: *** No rule to make target `cc'.  Stop.

Note that I have installed Xcode and Xcode developer command-line tools and in the folder /usr/bin I see the make and makefile properties.

What should I do to be able to compile with a makefile and a cc argument?

like image 265
Raphael Teubner Avatar asked Oct 16 '14 16:10

Raphael Teubner


2 Answers

Create a file called Makefile on the same path with this content:

CC = cc
CFLAGS = -std=c99 -pedantic -Wall
OBJECTS = filename.o

all: appname

filename.o: filename.c
    $(CC) $(CFLAGS) -c filename.c

appname: $(OBJECTS)
    $(CC) $(OBJECTS) -o appname

clean:
    rm -f *.o appname

Then run:

make

Of course, replace appname with the name of your program.

Note: There must be a "tab" (not spaces) before

$(CC) $(CFLAGS) -c filename.c

and

$(CC) $(OBJECTS) -o appname

and

rm -f *.o appname
like image 160
David Ranieri Avatar answered Sep 20 '22 08:09

David Ranieri


Enter image description here

Use:

make [filename]

./[filename]

If the filename is test.c and saved one the desktop then the commands are:

cd Desktop

make test

./test
like image 26
Anup Panchal Avatar answered Sep 23 '22 08:09

Anup Panchal