tags:

views:

89

answers:

5

Hi,

I am using Linux as my programming platform and C language as my programming language.

My problem is, I define a structure in my main source file( main.c):

struct test_st
{
   int state;
   int status;
};

So I want this structure to use in my other source file(e.g. othersrc.). Is it possible to use this structure in another source file without putting this structure in a header?

Thanks

+4  A: 

You can use pointers to it in othersrc.c without including it:

othersrc.c:

struct foo
{
  struct test_st *p;
};

but otherwise you need to somehow include the structure definition. A good way is to define it in main.h, and include that in both .c files.

main.h:

struct test_st
{
   int state;
   int status;
};

main.c:

#include "main.h"

othersrc.c:

#include "main.h"

Of course, you can probably find a better name than main.h

Matthew Flaschen
like in othersrc.c, I have to define struct test_st *lcst; ?
sasayins
the forward declaration is unneeded, just declare pointers.so you could write a function `void foo(test_st *lcst);` however you can see any of the feilds inside the structure, so anything that needs to work with the data inside it needs to be in main.c or you can put the structure definition in a header
Spudd86
+4  A: 

Putting it in a header file is the normal, correct way to declare types shared between source files.

Barring that, you can treat main.c as a header file and include it in the other file, then only compile the other file. Or you can declare the same struct in both files and leave a note to yourself to change it in both places.

drawnonward
+2  A: 

C support separate compilation.

Put structure declaration into a header file and #include "..." it in the source files.

Nikolai N Fetissov
+3  A: 

You can define the struct in each source file, then declare the instance variable once as a global, and once as an extern:

// File1.c
struct test_st
{
   int state;
   int status;
};

struct test_st g_test;

// File2.c
struct test_st
{
   int state;
   int status;
};

extern struct test_st g_test;

The linker will then do the magic, both source file will point to the same variable.

However, this is the worst possible coding practice, and I can't see any good reason to do it.

Lorenzo
+1  A: 
// use a header file.  It's the right thing to do.  Why not learn correctly?

//in a "defines.h" file:
//----------------------

typedef struct
{
   int state; 
   int status; 
} TEST_ST; 


//in your main.cpp file:
//----------------------

#include "defines.h"

TEST_ST test_st;


    test_st.state = 1;
    test_st.status = 2;




//in your other.ccp file:

#include "defines.h"

extern TEST_ST test_st;

   printf ("Struct == %d, %d\n", test_st.state, test_st.status);
Grimper
don't really need the typedef and some people don't like them
Spudd86