Stephen Wong
Stephen Wong

Reputation: 187

Multiple Definition with Multiple Source Files

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.

Upvotes: 0

Views: 901

Answers (3)

Raj
Raj

Reputation: 1

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

Upvotes: 0

tstanisl
tstanisl

Reputation: 14107

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

Upvotes: 0

Craig Estey
Craig Estey

Reputation: 33601

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++;
}

Upvotes: 3

Related Questions