0

I have the problem, that in CCS I encounter unexpected redefenition errors if I include headers.

Minimal example:

// main.c
#include "test.h"

int main(void)
{
    init();
    return 0;
}

with

// test.h
#ifndef TEST_H_
#define TEST_H_

int var;
void init();

#endif /* TEST_H_ */

and

// test.c
#include "test.h"

void init()
{
    var=0;
}

I get

error #10056: symbol "_var" redefined: first defined in "./main.obj"; redefined in "./test.obj"

on compilation. I'm pretty sure this should work in any C using IDE. What do I miss?

  • You should not define the same variable in multiple translation units. You define `var` in a header which causes it to be defined in every file where it is included. Normally you should declare `extern int var;` in the header and define it only in one C file. – Gerhardh Dec 15 '21 at 09:34
  • Shouldn't the include guards take care of that? It basically behaves as if those are ignored by CCS. – Vinzent Meier Dec 15 '21 at 09:38
  • No, each C file is compiled on its own. An include guard cannot prevent you from including the same content in all C files. That is the purpose of a header, after all. – Gerhardh Dec 15 '21 at 09:40
  • 1
    You might want to read this question: https://stackoverflow.com/q/1433204/6782754 – Gerhardh Dec 15 '21 at 09:43

1 Answers1

2

" I'm pretty sure this should work in any C using IDE". No it doesn't.

Every time you include test.h in a C file, the variable var is not only declared but also defined, hence the compilation error.

Include guards are not designed to avoid multiple definitions across translation units, but more to adress multiple inclusions of the same header file in a single translation unit.

See for example https://fr.wikipedia.org/wiki/Include_guard

The proper way to adress this issue is to only declare your variable in the header file:

extern int var;

and then define the variable only once in a C file (without extern).

int var;
Guillaume Petitjean
  • 2,408
  • 1
  • 21
  • 47