Linking files having multiple main function in c

2019-07-21 21:00发布

问题:

Is it possible to link two C files using makefile which calls each other function but both have a main function of their own.

e.g: C1.c uses function f() from C2.c.but both have main function and I want the main in C1.c to be considered as main only.

FILES.o=set.o hash.o printnfa.o input.o nfa.o dfa.o terp.o minimize.o defnext.o print_ar.o pairs.o squash.o signon.o print.o lex.o assort.o prnt.o printv.o bintoasc.o ferr.o onferr.o fputstr.o pchar.o driver.o searchenv.o hashadd.o esc.o 

PROGRAM= Lexer
INC := -I./debug.h -I./global.h -I./stack.h -I./set.h -I./hash.h
CFLAGS=-DMAIN
all: ${PROGRAM}

${PROGRAM}: ${FILES.o}
${CC} -o $@ ${CFLAGS} $(INC) $^ ${LDFLAGS} ${LDLIBS}

Now terp.c has a main and lex.c also has a main. I want only the main for lex.c to be considered.

回答1:

This will be specific for the linker you use. On Linux you can pass the --allow-multiple-definition flag to the linker in order to use only the first symbol in case of multiple definitions:

${PROGRAM}: ${FILES.o}
${CC} -Xlinker --allow-multiple-definition -o $@ ${CFLAGS} $(INC) $^ ${LDFLAGS} ${LDLIBS}

This will omit all errors about duplicate symbols and cause the linker to ignore any redefinitions. Make sure that the object file containing the symbol you wish to use comes before any redefinitions in the list.



回答2:

The short answer... NO ... it is NOT possible



回答3:

First of all I would recommend that you refactor the code so that you don't have functions that will be used by many programs in the same file as a main function.

Any way, here is an example on how to use the pre-processor to include only one of the main functions.

We have two source code files both with a main function plus one other function, foo() in file1.c and bar() in file2.c. foo() and baa() are called from both of the main functions.

By changing the MAIN_ALT value in the Makefile we can switch between the main functions:

Use the main function in file1.c:

DEFINES += -DMAIN_ALT=1

Use the main function in file2.c:

DEFINES += -DMAIN_ALT=2

Makefile:

OBJS = file1.o file2.o
DEFINES += -DMAIN_ALT=1
CFLAGS += -Wall $(DEFINES)
prog:$(OBJS) 
    $(CC) $(CFLAGS) -o $@ $^

file1.c:

#include "stdio.h"
#include "def.h"

void foo(){
    printf("From foo\n");
}

#if MAIN_ALT == 1
int main(){
    printf("Main in file1.c\n");
    bar();
    foo();
    return 0;
}
#endif

file2.c:

#include "stdio.h"
#include "def.h"

void bar(){
    printf("From bar\n");
}

#if MAIN_ALT == 2
int main(){
    printf("Main in file2.c\n");
    bar();
    foo();
    return 0;
}
#endif

def.h:

#ifndef __DEF_H__
#define __DEF_H__
void foo();
void bar();
#endif