cmakefilelinker

how to compile multiple instances of a source file linking to it different files.o


I have two files.c that contain the same methods(same name and parameters) but implemented differently for provide a approach independent from the implementation. how can I generate a single test file and compile it with both the two implementations without getting deployment errors?

graraphically Explained is:

file_one.c (same method names and parameters of file_two.c)

file_two.c

file_test.c

i want to:

compile -> file_test.c file_one.c

compile -> file_test.c file_two.c

in a makefile without make two copies of file_test.c


CC=gcc

CFLAGS=-c -Wall

all: test_matrice test_lista

test_matrice: grafi_test.c grafi_matrice.o

       $(CC) grafi_test.c grafi_matrice.o -o test_matrice 

test_lista: grafi_test.c grafi_liste.o

       $(CC) grafi_test.c grafi_liste.o -o test_lista 

grafi_matrice.o: grafi_matrice.c grafi_matrice.h

       $(CC) $(CFLAGS) grafi_matrice.c 

grafi_liste.o: grafi_liste.c grafi_liste.h

       $(CC) $(CFLAGS) grafi_liste.c 

clean: rm -rf *.o test_matrice test_lista


I get this error:

gcc grafi_test.c grafi_matrice.o -o test_matrice

grafi_test.c:4: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘attribute’ before ‘*’ token

grafi_test.c: In function ‘main’:

grafi_test.c:21: error: ‘graph’ undeclared (first use in this function)

grafi_test.c:21: error: (Each undeclared identifier is reported only once

grafi_test.c:21: error: for each function it appears in.)

grafi_test.c:21: error: ‘G’ undeclared (first use in this function)

make: * [test_matrice] Error 1


Thanks, Giorgio


Solution

  • This will do it:

    file_test_%: file_test.c file_%.c
        $(CC) $^ -o $@
    

    And if you want you can add a default rule:

    all: file_test_one file_test_two
    

    EDIT
    The trouble is with your declarations. If you have a function like this in grafi_matrice.c:

    void graph(int n)
      {
          ...
      }
    

    then code in another file like grafi_test.c cannot simply call it. The compiler attempts to compile grafi_test.c, reaches the line graph(3) and says "graph()? I know nothing about this." You must at least have a declaration in grafi_test.c (above the call) like this:

    void graph(int);
    

    The usual way to handle this is with header files, but that can wait.

    EDIT:
    The compiler still knows nothing about graph. You must learn about declarations or you will have no chance of success. To start, what does grafi_matrice.c say about graph?