1

I have two files, first_pass.c that includes mystring.h that describes mystring.c. While testing first_pass.c I did the following includes

#include "../src/mystring.c"
#include "../src/first_pass.c"
#include <gtest/gtest.h>

Everything worked well, until I had to define a structure in mystring.h. Simple as that

typedef struct Split {
    char *head;
    char *tail;
}Split;

And then I started to fail while compiling on error: ‘Split’ has a previous declaration as ‘typedef struct Split Split’

The requirements for the course are using C (not C++) and MAKE, so other testing frameworks, like Check were deprecated. I understand that it defines twice the struct, first time when it loads mystring.c and another on first_pass.c. What can I do about it?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
eugen-fried
  • 2,111
  • 3
  • 27
  • 48
  • Why are you defining the same structure twice ? – nouney Jul 19 '13 at 12:26
  • #including the source file (.c) is asking for trouble – doctorlove Jul 19 '13 at 12:45
  • As I answered below, I didn't had a choise. googletest files are simple headers with TEST macros, so to have the definition for my tested code I have to include it whole. This was my reference: http://meekrosoft.wordpress.com/2009/11/09/unit-testing-c-code-with-the-googletest-framework/ – eugen-fried Jul 19 '13 at 12:49

3 Answers3

2

Use header guards to prevent the inclusion of headers more than once.

http://en.wikipedia.org/wiki/Include_guard

one suggestion add header files to a C files not C files to another C file.

pradipta
  • 1,718
  • 2
  • 13
  • 24
  • 1
    You're right! I've read about it, but didn't think that this is the case. Thank you! I'll give you the check because you were first. – eugen-fried Jul 19 '13 at 12:31
2

Best way: don't include '.c' files but compile then to seperate '.o' and link tem all together.

If multiply inclusion oh a header like mystring.h is unevitable, look for for header guards, for example here in SO

Community
  • 1
  • 1
Ingo Leonhardt
  • 9,435
  • 2
  • 24
  • 33
1

You need to guard your structure definition as below

#ifndef SOME_GUARD_NAME
#define SOME_GUARD_NAME

typedef struct Split {
    char *head;
    char *tail;
}Split;

#endif

Since you are including ".c" files so please have a look here to avoid all this mess.

Community
  • 1
  • 1
Dayal rai
  • 6,548
  • 22
  • 29
  • I didn't had a choise. googletest files are simple headers with TEST macros, so to have definition for my tested code I have to include it whole. But thank you for a good educational link. – eugen-fried Jul 19 '13 at 12:43