Thread: #ifndef

  1. #1
    Registered User
    Join Date
    Jul 2004
    Posts
    91

    #ifndef

    when we create header files i know you can do it like this..

    blah.h
    Code:
    #ifndef BLAH_H
    #define BLAH_H
    
    void blah();
    
    #endif
    in main.c if i was to include this header file i would do
    #include "blah.h"

    but if i didnt have the #ifndef stuff, this could still work couldnt it?
    so then whats the point for the #ifndef stuff?

    and say if blah was named blah.c i could do #include "blah.c" without the ifndef stuff aswell right?

  2. #2
    ---
    Join Date
    May 2004
    Posts
    1,379
    its so that it is not included more than once.

    Code:
    #ifndef BLAH_H //if BLAH_H is not defined (BLAH_H is just a label for the following code)
    #define BLAH_H //if BLAH_H is not previously defined then define it :)
     
    ...
     
    #endif //self explanatory (i hope)
    read this faq entry
    http://faq.cprogramming.com/cgi-bin/...&id=1043284392
    Last edited by sand_man; 08-20-2004 at 12:52 AM.

  3. #3
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    Simiple test:
    header1.h
    Code:
    #ifndef HEADER1_H_
    #define HEADER1_H_
    
    void foo (void)
    {
      printf("I'm in foo()\n");
    }
    
    #endif
    header2.h
    Code:
    void bar (void)
    {
      printf("I'm in bar()\n");
    }
    main.c
    Code:
    #include <stdio.h>
    #include "header1.h"
    #include "header2.h"
    #include "header1.h"
    #include "header2.h"
    
    int main(void)
    {
      foo();
      bar();
      return 0;
    }
    Compile and look at the results

  4. #4
    Registered User
    Join Date
    Feb 2003
    Posts
    175
    I did exactly what Thantos said, but included #defines and int/char declartions.

    Why doesn't #define and int/char declaration in header2.h file give error? Why only functions??

    Please let me know..

  5. #5
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    Way to bump an old thread.

    #defines don't give an error because the preprocessor doesn't care if there are multiple declartions, it just uses the newest one

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. #ifndef explanation?
    By Zooker in forum C Programming
    Replies: 2
    Last Post: 02-12-2009, 06:59 AM
  2. Code review
    By Elysia in forum C++ Programming
    Replies: 71
    Last Post: 05-13-2008, 09:42 PM
  3. Warning on an ifndef directive
    By DavidP in forum C++ Programming
    Replies: 2
    Last Post: 08-02-2007, 01:31 AM
  4. #ifndef wrapper to reference dll
    By joeyzt in forum C++ Programming
    Replies: 2
    Last Post: 06-21-2004, 01:30 PM
  5. ifndef
    By mayfda in forum C++ Programming
    Replies: 3
    Last Post: 01-13-2003, 03:29 PM