Adam Barča
Adam Barča

Reputation: 91

Makefile variable to c program

Hello i need help with makefile variables.

make build //(compiler server) 
make run PORT=something //(run server on port something)

I need save this variable and post to the server.c and client.c Here is my Makefile

SERVER=server
CLIENT=client
FILES=src/server.c src/client.c
CFLAGS=-std=gnu99 -Wall -Wextra -Werror -pedantic
CC=gcc
build:
        $(CC) $(CFLAGS) -o $(SERVER) src/server.c
        $(CC) $(CFLAGS) -o $(CLIENT) src/client.c
run:
        ./server
clean:
        $(RM) *.o src/$(CLIENT) src/$(SERVER

Upvotes: 0

Views: 262

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 754860

A plausible outline for a compile-time decision about port number might be:

SERVER   = server
CLIENT   = client
SERVER.c = src/server.c
CLIENT.c = src/client.c
CFLAGS   = -std=gnu99 -Wall -Wextra -Werror -pedantic
PORT     = 9823
DFLAGS   = -DPORT=$(PORT)
CC       = gcc

all:   build

build: $(CLIENT) $(SERVER)

$(CLIENT): $(CLIENT.c)
        $(CC) $(CFLAGS) $(DFLAGS) -o $(CLIENT) $(CLIENT.c)

$(SERVER): $(SERVER.c)
        $(CC) $(CFLAGS) $(DFLAGS) -o $(SERVER) $(SERVER.c)

run: $(CLIENT) $(SERVER)
        ./$(SERVER)

clean:
        $(RM) *.o $(CLIENT) $(SERVER)

The code for the client and the server contains code such as this, preferably in a common header:

#ifndef PORT
#define PORT 1234
#endif

and references PORT where the port number is needed.

If it is strictly a run-time decision, then maybe you use:

SERVER   = server
CLIENT   = client
SERVER.c = src/server.c
CLIENT.c = src/client.c
CFLAGS   = -std=gnu99 -Wall -Wextra -Werror -pedantic
PORT     = 9823
CC       = gcc

all: build

build: $(CLIENT) $(SERVER)

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

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

run: $(CLIENT) $(SERVER)
        ./$(SERVER) -p $(PORT)

clean:
        $(RM) *.o $(CLIENT) $(SERVER)

You'd also need to tell the client to connect to the given port number, of course. You should still have a default port number that is shared by both client and server in some common header.

You might use a hybrid of these solutions, where you define the default port number in the build process and use it in the run rule too.

Upvotes: 1

Related Questions