Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

How do I use header files in C++?

  • 06-03-2002 12:11PM
    #1
    Posts: 431 ✭✭


    Apologies if this question was asked before.

    Can anyone tell me how to use header files in C++?
    It's confusing at the moment and I haven't got a clue the way things are declared within them.

    Also, what does #ifndef do at the top of the header file?

    Thanks for any help, it would be great


Comments

  • Registered Users, Registered Users 2, Paid Member Posts: 2,032 ✭✭✭lynchie


    In C++, usually you define your class in the header file while you put your implementation of your class in a .cpp file. Using it is as simple as putting a #include "myheaderfile.h" at the top of your .cpp file.

    A #ifndef command (like #if and #ifdef) can be used to conditionally include lines of text

    i.e.

    #ifndef MY_VAR //If MY_VAR has not already been defined
    #define MY_VAR xxx
    #endif


  • Closed Accounts Posts: 536 ✭✭✭flyz


    Header files are a method of tidying things up in C++.
    If you're declaring all your variables at the top of your cpp file then it's easier to put them all into the header file.
    Also with classes and structures it tends to be easier to have them declared in header files than in the cpp file.

    Also if you need to access the same variable / class from 2 cpp files then you can access that variable by including the header file to both cpp files.
    Thats where the #ifndef stuff comes in too , if you have the same header file included in more than one cpp file then the compiler will think that the variables you've defined in the header file are defined twice. that's why you put in the ifdef so that the compiler will only 'declare' the variables once.

    #ifndef MY_HEADER_H
    #define MY_HEADER_H

    //all the variables you define in here

    #endif


Advertisement