简体   繁体   中英

Function declaration with struct parameter in header file in C

My teachers words "Create a header file and put all function declarations of the functions you have in your .c file. Also put your structs and macros in the header. Make sure to "protect" this file from being included multiple times"

Okay so I protect my header by using

#ifndef List_h
#define List_h
//My header code
#endif

I have put all my structs in this header file and included it in my .c files and everything seem to work fine. I do not use any macros so I do not have that. The problem comes when I try to do my function declaration. This is what my function looks like:

int FunctionName(struct NameOfStruct *PointerToStruct){
//Code here
}

I have then tried to declare my function in the header file like this:

int FunctionName(struct);

But get an error "Declaration of 'struct NameOfStruct' will not be visible outside of this function"

I have tried:

int FunctionName(struct NameOfStruct *PointerToStruct);

but get the same error. How I am supposed to declare a function in the header file? Nothing I have found on google seem to work. What am I doing wrong?

You need to define (or at least declare) struct NameOfStruct before the function declaration.

struct NameOfStrunct {
    …
};
int FunctionName(struct NameOfStruct *PointerToStruct);

The order matters. The explanation for the error message is that the first mention of struct NameOfStruct declares the structure name for the scope in which it is found. If the first mention is as a toplevel declaration, the name remains valid for the rest of the file. If it's inside a function definition, the name remains valid only while compiling this function. If it's in a function prototype, the name remains valid only for the prototype itself, and that doesn't make sense since you wouldn't be able to use the same structure to pass an argument to the function or in the definition of the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM