John Ward
John Ward

Reputation: 15

C - multiple definition with makefile

I am trying to compile my C program using make and I've come across this problem that I can't quite understand. I have 3 files in the 'calc' folder of my project: add.c sub.c and main.c. I have my Makefile located in the root folder of my project, which has the calc folder that I mentioned in it. This is what my Makefile looks like:

CC=gcc
OBJECTS=obj/main.o obj/add.o obj/sub.o 

elf/new: ${OBJECTS}
        ${CC} -o elf/new ${OBJECTS}
obj/main.o: calc/main.c
    ${CC} -c -g calc/main.c -o obj/main.o
obj/add.o: calc/add.c
    ${CC} -c -g calc/add.c -o obj/add.o
obj/sub.o: calc/sub.c
    ${CC} -c -g calc/sub.c -o obj/sub.o

clean:
    rm obj/${OBJECTS} elf/new

When I type 'make' into the terminal to compile, I get an error like this:

gcc -c -g calc/add.c -o obj/add.o
gcc -c -g calc/sub.c -o obj/sub.o
gcc -o elf/new obj/main.o obj/add.o obj/sub.o 
obj/add.o: In function `add':
/home/bigger/workspace/test/calc/add.c:1: multiple definition of `add'
obj/main.o:/home/bigger/workspace/test/calc/add.c:1: first defined here
obj/sub.o: In function `sub':
/home/bigger/workspace/test/calc/sub.c:1: multiple definition of `sub'
obj/main.o:/home/bigger/workspace/test/calc/sub.c:1: first defined here
collect2: error: ld returned 1 exit status
makefile:5: recipe for target 'elf/new' failed
make: *** [elf/new] Error 1

And my code are there:

bigger@linux:~/workspace/test> cat calc/add.c 
int add(int a, int b){
    return a+b;
}


bigger@linux:~/workspace/test> cat calc/sub.c 
int sub(int a, int b) {
    return a-b;
}


bigger@linux:~/workspace/test> cat calc/main.c 
#include <stdio.h>
#include "add.c"
#include "sub.c"

int main(int argc, char* argv[])
{
    int a = 10;
    int b = 5;
    printf("add: %d\nsub:%d\n", a+b, a-b);
    return 0;
}

Upvotes: 1

Views: 3988

Answers (1)

Frisco Rose
Frisco Rose

Reputation: 36

When you include it is making the functions add and sub part of your main.c, then when you make you are linking main (which already has the functions by include) to the add and sub objects which have the same function symbols. You need to include header files with function declarations rather than include function definitions. See http://www.cprogramming.com/declare_vs_define.html for a longer discussion.

Upvotes: 2

Related Questions