[C] When creating code by separating it into a header file, where should the user declaration structure be entered?

Asked 2 years ago, Updated 2 years ago, 70 views

While writing the header file and writing the code, I have a question, so I'm asking you.

-- myheader.h

#pragma once

typedef struct node {
    int data;
    struct node *next;
}NODE;

typedef struct {
    int count;
    NODE *head;
}plist;

void get_group(plist** group);

You created this myheader.h file and a function to enter this header in the myheader.c file.

-- myheader.c

#include<stdio.h>

void get_group(plist** group)
{ // omitted
}

My questions are as follows.

(1) If you declare a custom first aid only in the header file, a red line is displayed on the screen, indicating that it is an error. But if you declare this user structure on myheader.h and myheader.c, you no longer see a red line on the screen. What I'm confused about is which of the two files should I declare this user structure? Declare only in header file / Declare only in c file / Declare both in which way is right? It seems to be caused by something I overlook about the relationship between the header file and its c file ㅠㅜㅠ

(2) Whether it is okay to include another header file in the header file While I was writing the code, I needed to write a function of the header such as string.h in the header file that I defined. However, I am confused whether I should include this header in myheader.h or myheader.c...

If you have any data related to the header file, or if there is anyone who can help you, please help me (Crying) Please! (If there is another error in my code that I didn't find, please comment!)

header struct c

2022-09-21 23:08

1 Answers

I'd like you to think of header files as a kind of interface.

Whenever I look at the header file, I'm like, "Ah~"It means that you can see that this and that functionality is provided.

The structure must, of course, be defined in the header file.

This is because you can put the structure as a parameter or define it as a pointer and receive it as a return value.

You can use the top of the c file as below.

#include<stdio.h> 
#include "myheader.h"

Of course, if you have to use what is declared a.h in b.h, a.h must be included in b.h. You can judge this part.

You may think that the h file may be included several times, but we prevent it by using the #pragmaence code or the prevention code below.

 #ifndef MY_H_ /* Prevention of duplication */
#define MY_H_   
...
...
#endif 


2022-09-21 23:08

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.