Thread: Header files question

  1. #1
    Registered User Ivory348's Avatar
    Join Date
    Oct 2019
    Posts
    75

    Header files question

    In response to one of my Cboard queries I was told by a responding OP that my header file treatment was wrong. The way I did it, was conform an Internet tutorial. This is how (re below). Please tell me what is wrong and also how it should be done. I understand that the "externs" in the example signify that no memory is to be allotted. I was also told that no function definitions should be in a header file. Where then should they be defined?

    Code:
    //in foo.h
    
        #ifndef temp
        #define temp
             extern int foo(int x)
        #end if
        extern int foo(int x)
        {
                   return x+5;
        }
    
    //in main.c
        #include "foo.h"
        int main(void)
        {
              int y  =  foo(3);
              printf("%d\n",y)
        }

  2. #2
    Registered User
    Join Date
    May 2012
    Location
    Arizona, USA
    Posts
    948
    The conventional way is to put declarations in a header file and definitions in a source file:

    foo.h:
    Code:
    #ifndef FOO_H
    #define FOO_H
    
    // declarations
    
    extern int myvariable;
    int foo(int x);
    
    #endif
    foo.c:
    Code:
    #include "foo.h"
    
    // definitions
    
    int myvariable;
    
    int foo(int x)
    {
        return x+5;
    }
    main.c:
    Code:
    #include <stdio.h>
    #include "foo.h"
    
    int main(void)
    {
        int y  =  foo(3);
        printf("%d\n",y)
    }
    "extern" means "this object is declared here but defined elsewhere". It's usually used to declare variables in a header file. It's optional (that is, it's not needed) for function declarations.

  3. #3
    Registered User Ivory348's Avatar
    Join Date
    Oct 2019
    Posts
    75
    [QUOTE=christop;1292211]The conventional way , <snipped>

    What you say is clear. Thank you. The strange thing is that I have an application where that approach errors out. But there are more peculiarities with that code.
    Last edited by Ivory348; 12-19-2019 at 11:32 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. next dumb question re header files
    By cooper1200 in forum C Programming
    Replies: 2
    Last Post: 04-25-2019, 02:33 AM
  2. Header files question
    By Programmer_P in forum C++ Programming
    Replies: 8
    Last Post: 05-14-2009, 01:16 PM
  3. quick question about header files
    By linucksrox in forum C++ Programming
    Replies: 11
    Last Post: 08-24-2005, 09:24 PM
  4. Novice question on header files
    By hern in forum C++ Programming
    Replies: 1
    Last Post: 07-30-2005, 10:11 AM
  5. question about header files
    By ArseMan in forum C++ Programming
    Replies: 2
    Last Post: 09-21-2001, 02:33 AM

Tags for this Thread