0

How can I solve the error: unterminated #ifndef when am trying to use header files with my defined functions in C ?

In file included from test.c:1:
main.h:1: error: unterminated #ifndef
    1 | # ifndef _MAIN_H_
      |

this is the code

# ifndef _MAIN_H_
# ifdef _MAIN_H_

int now(void);

# endif
~        

I though #endif solves it all but failed.

  • 2
    " #endif solves it all" `#endif` closes exactly one `#if` or `#else` or `#elif`. Not all that are open. – Gerhardh Dec 08 '22 at 09:40
  • Welcome to StackOverlow. Please take a [tour] and see [ask]. Specifically you'll need to post a [mre]. In general `#endif` does close [one] `#ifndef` but without seeing your code it's hard to say what went wrong. – wohlstad Dec 08 '22 at 09:41
  • ``` C # ifndef _MAIN_H_ # ifdef _MAIN_H_ int now(void); # endif – Raymond Kasumba Dec 08 '22 at 09:44
  • 1
    Read this: https://stackoverflow.com/questions/27810115/what-exactly-do-c-include-guards-do – Jabberwocky Dec 08 '22 at 10:12

1 Answers1

3

The #ifdef should be a #define for you to have working #include guard. As originally written the #ifndef is missing the matching #endif.

Symbols that start with underscore followed by an uppercase letter are reserved (6.4.2.1). Use MAIN_H instead.

You could also use #pragma once which is a non-standard, but widely supported, alternative to the include guard.

Leave out the ~ of the code listing as it's vi's EOF marker and not part of your header file.

Allan Wind
  • 23,068
  • 5
  • 28
  • 38
  • 1
    Regarding search for dupes, there's usually no need for that, just go to https://stackoverflow.com/tags/c/info, scratch your head for a second: "this would be a question about the preprocessor", scroll down to FAQ -> preprocessor, grab [Creating your own header file in C](https://stackoverflow.com/questions/7109964/creating-your-own-header-file-in-c), copy/pasta into close as dupe. In this case I voted to close the question as simple typo since it's unlikely that the particular problem of the OP is a recurring one. – Lundin Dec 08 '22 at 10:31
  • @Lundin LOL. It took me an embarrassing long time to figure how to navigate to that page (click or search for tag, then click "Learn more..."). – Allan Wind Dec 08 '22 at 10:39