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):
C support separate compilation.
Put structure declaration into a header file and #include "..."
it in the source files.
It is perfectly reasonable to be inclusive with structs by leaving them in the source file instead. This is encapsulation. However if you're going to redefine struct multiple times in multiple source files then you might as well define the struct once in a header file instead and include that file as necessary.
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
Header file /* include this header file in both file1.c and file2.c
strcut a {
};
struct b {
};
so header file included the declaration of both structures .
file 1.c
strcut a xyz[10];
--> struct a defined here
to use struct b here in this file
extern struct b abc[20];
/* now can use in this file */
file2.c
strcut b abc[20]; /* defined here */
to use strcut a defined in file1.c
use extern struct a xyz[10]
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.
// 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);