RErik
RErik

Reputation: 27

Makefile errors with 2 executables: multiple definitions of 'main'

I have a project which requires two separate executables, each with a 'main' function. They share a header file and another file with function definitions. The makefile I'm using gives me the "multiple definition of `main'" error. I want to compile both executables into the "./bld" folder. Can someone give me some pointers on what I'm doing wrong? Thanks.

   CC := gcc
   CFLAGS := -g -Wall -Werror


   RM := rm
   MKDIR := mkdir -p
   OUT_DIR := bld
   OBJ_DIR := $(OUT_DIR)/obj


   SOURCES := $(wildcard *.c)


   OBJECTS := $(addprefix $(OBJ_DIR)/, $(SOURCES:.c=.o))


   TARGET := $(addprefix $(OUT_DIR)/, $(SOURCES:.c=))


   .PHONY: all clean

   all: $(TARGET)

   clean:
       $(RM) -rf $(OUT_DIR)

   $(TARGET): $(OBJECTS)
       $(CC) $(CFLAGS) $^ -o $@

   $(OBJ_DIR)/%.o: %.c
       @$(MKDIR) $(dir $@)
       $(CC) $(CFLAGS) -c $< -o $@

Upvotes: 0

Views: 965

Answers (2)

Mewen LE RESTE
Mewen LE RESTE

Reputation: 66

For my C/C++ projects I use a different type of template for my Makefile, but here are what the template would look like for your case

SRC1 = main1.c \
      other.c

OBJ1 =   $(SRC1:.c=.o)

NAME1 =  executableName1

SRC2 = main2.c \
      other.c

OBJ2 =   $(SRC2:.c=.o)

NAME2 =  executableName2

all: $(NAME1) $(NAME2)

$(NAME1): $(OBJ1)
        gcc -o $(NAME1) $(OBJ1)

$(NAME2): $(OBJ2)
        gcc -o $(NAME2) $(OBJ2)

clean:
        rm -Rf $(OBJ1)
        rm -Rf $(OBJ2)

fclean: clean
        rm -Rf $(NAME1)
        rm -Rf $(NAME2)

re: fclean all

.PHONY: all clean fclean re

As you see I don't use *.c, because like that I could have all of my source code in the same folder without compiling files I don't want for each executables. Using this Makefile you can build both executables by calling "make" or "make all" and you can build each executables separately by calling "make executableName1" and "make executableName2". If you want to keep your template as it is, I suggest you to make some little research on Makefile to understand both templates and see how to merge them ;)

Upvotes: 1

Mewen LE RESTE
Mewen LE RESTE

Reputation: 66

Looking at your Makefile you seem like calling only one time gcc to build your two executables. To build two executables you need to call two times gcc one with the sources of the first executable, and the other with the sources of the second executable

Upvotes: 0

Related Questions