Answer the question
In order to leave comments, you need to log in
Does the structure declared in the header file not work?
Hello. I have a structure declared in the header, but for some reason I cannot
use it in main.c.
I have no idea what he doesn't like, I can declare a variable with a structure type, but I can't access its member.
Here is the code:
header.h
#ifndef _HEADER_H_
#define _HEADER_H_
typedef struct htype {
int num;
} htype_t;
#endif
#include "stdio.h"
#include "header.h"
htype_t htval;
htval.num = 10;
int main(int argc, char* argv[]) {
printf("%i\n", htval.num);
}
$ gcc main.c -o prog
main.c:5:6: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘.’ token
5 | htval.num = 10;
| ^
Answer the question
In order to leave comments, you need to log in
#include <stdio.h>
#include "header.h"
int main(int argc, char* argv[]) {
htype_t htval;
htval.num = 10;
printf("%i\n", htval.num);
}
So what is it all about htval.num = 10;
:
It looks like a statement . In C and C++, statements can only be inside functions. Nowhere else. This is a grammar requirement, i.e. elementary syntax of these languages. Why did you write the statement in a "blank field" outside of the function? This is incorrect from the point of view of the syntax of the language.
To put it simply, in C and C++, code is written inside functions, not outside.
PS Your question has nothing to do with "a structure declared in a header file". Neither structures nor header files have anything to do with it.
htype_t htval; htval.num = 10;
htype_t htval = {.num = 10};
htype_t htval = {10};
htype_t htval;
int main(int argc, char* argv[]) {
htval.num = 10;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question