Howard Shane
Howard Shane

Reputation: 956

Linux C: error of redefinition of in include headers

I have a project, which has below header include map:

main.c <- main.h <- tcphelper.h <- tcptest.h <- util.h
                 <- udptest.h    <------------- util.h

In util.h, I defined a function prototype of struct cpu_usage:

void get_cpu_usage(struct cpu_usage *cu);

Now when I compile this project by GCC, I have this redefinition error. How do solve this problem?

thanks!

In file included from udptest.h:15:0,
                 from main.h:10,
                 from main.c:7:
util.h:27:8: error: redefinition of struct cpu_usage
 struct cpu_usage{
        ^
In file included from tcptest.h:14:0,
                 from tcphelper.h:10,
                 from main.h:9,
                 from main.c:7:
util.h:27:8: note: originally defined here
 struct cpu_usage{
        ^

Upvotes: 2

Views: 1605

Answers (1)

Daniel Frużyński
Daniel Frużyński

Reputation: 2189

You need to add Include guards to your header files to prevent including their contents multiple times. Example:

#ifndef UTIL_H_INCLUDED
#define UTIL_H_INCLUDED

/* header contents goes here */

#endif /* UTIL_H_INCLUDED */

Upvotes: 7

Related Questions