Joker
Joker

Reputation: 21

Makefile in C to get an executable

How can I get a makefile of my C program that will build/compile my program and generates an executable.This executive should be able to run my c program???

Upvotes: 1

Views: 259

Answers (2)

David Ranieri
David Ranieri

Reputation: 41017

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

CC = gcc
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

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

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

and

$(CC) $(OBJECTS) -o appname

Then run:

make

EDIT: An example:

david@debian:~$ cat demo.c
#include <stdio.h>

int main(void) 
{
    return 0;
}

david@debian:~$ cat Makefile
CC = gcc
CFLAGS = -std=c99 -pedantic -Wall
OBJECTS = demo.o

all: demo

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

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

david@debian:~$ make
gcc -std=c99 -pedantic -Wall -c demo.c
gcc demo.o -o demo

Upvotes: 0

Deduplicator
Deduplicator

Reputation: 45654

Save the makefile as makefile or Makefile:

.PHONY: all
all : progname
progname: all-objects
  1. .PHONY to mark the target all as not a file-target
  2. all is the first and thus default-target, depends on progname (Just so make all works)
  3. progname depends on all the object-files, and will thus link them together.
  4. The object-files are built using builtin rules.

If you want to override the default-action of a rule, write your own recipe.
Each command-line must be indented one tab (do not use spaces).

Reference of GNU make: http://www.gnu.org/software/make/manual/make.html
Reference of builtin rules: https://www.gnu.org/software/make/manual/html_node/Catalogue-of-Rules.html

Upvotes: 2

Related Questions