Multiple Definition with Multiple Source Files

757 Views Asked by At

I'm currently writing a C program with multiple header and source files. I have been running into the problem of multiple definition of function foo.

I understand that I am violating the One Definition Rule, but I am not quite sure how to work around this issue. I have source files for the two objects, obj1.c and obj2.c. Because header.h iis included in more than one .c file, it is causing this error.

Are there workarounds other than eliminating all .c files other than main.c?

//header.h (with include guards)
void helper(){}

//obj1.h
// Include function definitions for obj1.c

//obj1.c
#include "obj1.h"
#include "header.h"

//obj2.h
// Include function definitions for obj2.c

//obj2.c
#include "obj2.h"
#include "header.h"

//main.c
#include "obj1.h"
#include "obj2.h"


Thank you.

3

There are 3 best solutions below

1
On

open the Project file in notepad, and you will notice the one file has 2 entries.

0
On

In header.h, you have:

void helper(){}

This is a definition [and not merely a declaration].

You want a declaration:

void helper();

In one [and only one] of your .c files, you want a definition:

void
helper()
{
     // do helpful things ...
     helper_count++;
}
0
On

Make it a static inline function. Ensure that the header has guards preventing multiple includes from a single translation unit.

// header.h
#ifndef HEADER_H
#define HEADER_H

static inline void helper() {}

#endif