G
G
German2020-08-13 22:25:21
C++ / C#
German, 2020-08-13 22:25:21

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


main.c
#include "stdio.h"
#include "header.h"

htype_t htval;
htval.num = 10;

int main(int argc, char* argv[]) {
  printf("%i\n", htval.num);
}

Error:
$ gcc main.c -o prog
main.c:5:6: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘.’ token
    5 | htval.num = 10;
      |      ^


What is the problem?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
Ivan Solomennikov, 2020-08-13
@mrjbom

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

int main(int argc, char* argv[]) {

  htype_t htval;
  htval.num = 10;

  printf("%i\n", htval.num);
}

A
AnT, 2020-08-13
@TheCalligrapher

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.

J
jcmvbkbc, 2020-08-13
@jcmvbkbc

htype_t htval;
htval.num = 10;

And why not, for a change, write according to the rules of the language, for example, like this (if, after all, C):
htype_t htval = {.num = 10};
or like this (if, after all, C ++):
htype_t htval = {10};
or even like this:
htype_t htval;

int main(int argc, char* argv[]) {
    htval.num = 10;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question