Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate Symbol in C

I have two source files:

Source FIle 1 (assembler.c):

#include "parser.c"
int main() {
    parse_file("test.txt");
    return 0;
}

Source File 2 (parser.c):

void parse_file(char *config_file);
void parse_file(char *src_file) {
    // Function here
}

For some reason, when compiling it is giving me the following error: duplicate symbol _parse_file in ./parser.o and ./assembler.o for architecture x86_64

Why is it giving me a duplicate symbol for parse_file? I am just calling the function here... No?

like image 358
darksky Avatar asked Oct 03 '11 18:10

darksky


People also ask

How to remove all duplicate characters in a string in C?

C Program to Remove All Duplicate Characters in a String using While Loop C Program to Remove All Duplicate Characters in a String using Function Use the following algorithm to write a program to remove the duplicate character from a string; as follows: Start program. Take input string from user, store it in some variable.

How do I get the destination of a duplicate string?

The duplicate string’s destination is declared as a char pointer at Line 7. The strdup () function appears at Line 10. It’s format uses the original string as the only argument. The duplicate is returned, or the NULL pointer in case of failure.

How do I copy a string in C?

The C library function to copy a string is strcpy (), which (I’m guessing) stands for string copy. The dst is the destination, src is the source or original string.


1 Answers

First off, including source files is a bad practice in C programming. Normally, the current translation unit should consist of one source file and a number of included header files.

What happens in your case is that you have two copies of the parse_file function, one in each translation unit. When parser.c is compiled to an object file, it has its own parse_file function, and assembler.c also has its own.

It is the linker that complains (not the compiler) when given two object files as an input, each of which contains its own definition of parse_file.

You should restructure your project like this:

parser.h

void parse_file(char *);

parser.c

void parse_file(char *src_file) {
    // Function here
}

assembler.c

/* note that the header file is included here */
#include "parser.h"

int main (void) {
    parse_file("test.txt");
    return 0;
}
like image 126
Blagovest Buyukliev Avatar answered Nov 03 '22 03:11

Blagovest Buyukliev