Friday, February 4, 2022

[SOLVED] How to use a defined struct from another source file?

Issue

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?


Solution

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



Answered By - Matthew Flaschen
Answer Checked By - Pedro (WPSolving Volunteer)