2.11 — Header files

Headers, and their purpose

As programs grow larger (and make use of more files), it becomes increasingly tedious to have to forward declare every function you want to use that is defined in a different file. Wouldn’t it be nice if you could put all your forward declarations in one place and then import them when you need them?

C++ code files (with a .cpp extension) are not the only files commonly seen in C++ programs. The other type of file is called a header file. Header files usually have a .h extension, but you will occasionally see them with a .hpp extension or no extension at all. The primary purpose of a header file is to propagate declarations to code files.

Using standard library header files

Consider the following program:

This program prints “Hello, world!” to the console using std::cout. However, this program never provide a definition or declaration for std::cout, so how does the compiler know what std::cout is?

The answer is that std::cout has been forward declared in the “iostream” header file. When we #include <iostream>, we’re requesting that the preprocessor copy all of the content (including forward declarations for std::cout) from the file named “iostream” into the file doing the #include.

Key insight

When you #include a file, the content of the included file is inserted at the point of inclusion. This provides a useful way to pull in declarations from another file.

Consider what would happen if the iostream header did not exist. Wherever you used std::cout, you would have to manually type or copy in all of the declarations related to std::cout into the top of each file that used std::cout! This would require a lot of knowledge about how std::cout was implemented, and would be a ton of work. Even worse, if a function prototype changed, we’d have to go manually update all of the forward declarations. It’s much easier to just #include iostream!

When it comes to functions and objects, its worth keeping in mind that header files typically only contain function and object declarations, not function and object definitions (otherwise a violation of the one definition rule could result). std::cout is forward declared in the iostream header, but defined as part of the C++ standard library, which is automatically linked into your program during the linker phase.

Best practice

Header files should generally not contain function and variable definitions, so as not to violate the one definition rule. An exception is made for symbolic constants (which we cover in lesson 4.13 -- Const, constexpr, and symbolic constants).

Writing your own header files

Now let’s go back to the example we were discussing in a previous lesson. When we left off, we had two files, add.cpp and main.cpp, that looked like this:



(If you’re recreating this example from scratch, don’t forget to add add.cpp to your project so it gets compiled in).

In this example, we used a forward declaration so that the compiler will know what identifier add is when compiling main.cpp. As previously mentioned, manually adding forward declarations for every function you want to use that lives in another file can get tedious quickly.

Let’s write a header file to relieve us of this burden. Writing a header file is surprisingly easy, as header files only consist of two parts:

  1. A header guard, which we’ll discuss in more detail in the next lesson (2.12 -- Header guards).
  2. The actual content of the header file, which should be the forward declarations for all of the identifiers we want other files to be able to see.

Adding a header file to a project works analogously to adding a source file (covered in lesson 2.8 -- Programs with multiple code files). If using an IDE, go through the same steps and choose “Header” instead of “Source” when asked. If using the command line, just create a new file in your favorite editor.

Best practice

Use a .h suffix when naming your header files.

Header files are often paired with code files, with the header file providing forward declarations for the corresponding code file. Since our header file will contain a forward declaration for functions defined in add.cpp, we’ll call our new header file add.h.

Best practice

If a header file is paired with a code file (e.g. add.h with add.cpp), they should both have the same base name (add).

Here’s our completed header file:


In order to use this header file in main.cpp, we have to #include it (using quotes, not angle brackets).



When the compiler compiles the #include "add.h" line, it copies the contents of add.h into the current file at that point. Because our add.h contains a forward declaration for function add, that forward declaration will be copied into main.cpp. The end result is a program that is functionally the same as the one where we manually added the forward declaration at the top of main.cpp.

Consequently, our program will compile and link correctly.

Best practice

A code file should #include its paired header file (if it exists). If you’re curious as to why, see nascardriver’s comment here.


If you get a compiler error indicating that add.h isn’t found, make sure the file is really named add.h. Depending on how you created and named it, it’s possible the file could have been named something like add (no extension) or add.h.txt or add.hpp. Also make sure it’s sitting in the same directory as the rest of your code files.

If you get a linker error about function add not being defined, make sure you’ve included add.cpp in your project so the definition for function add can be linked into the program.

Angled brackets vs quotes

You’re probably curious why we use angled brackets for iostream, and double quotes for add.h. The answer is that angled brackets are used to tell the preprocessor that we are including a header file that was included with the compiler, so it should look for that header file in the system directories. The double-quotes tell the preprocessor that this is a user-defined header file we are supplying, so it should look for that header file in the current directory containing our source code first. If it doesn’t find the header file there, it will check any other include paths that you’ve specified as part of your compiler/IDE settings. That failing, it will fall back to checking the system directories.


Use angled brackets to include header files that come with the compiler. Use double quotes to include any other header files.

Why doesn’t iostream have a .h extension?

Another commonly asked question is “why doesn’t iostream (or any of the other standard library header files) have a .h extension?”. The answer is that iostream.h is a different header file than iostream! To explain requires a short history lesson.

When C++ was first created, all of the files in the standard runtime library ended in a .h stuffix. Life was consistent, and it was good. The original version of cout and cin were declared in iostream.h. When the language was standardized by the ANSI committee, they decided to move all of the functionality in the standard library into the std namespace to help avoid naming conflicts with user-defined identifiers. However, this presented a problem: if they moved all the functionality into the std namespace, none of the old programs (that included iostream.h) would work any more!

To work around this issue, a new set of header files was introduced that use the same names but lack the .h extension. These new header files have all their functionality inside the std namespace. This way, older programs that include #include <iostream.h> do not need to be rewritten, and newer programs can #include <iostream>.

In addition, many of the libraries inherited from C that are still useful in C++ were given a c prefix (e.g. stdlib.h became cstdlib). The functionality from these libraries was also moved into the std namespace to help avoid naming collisions.

Best practice

When including a header file from the standard library, use the no extension version (without the .h) if it exists. User-defined headers should still use a .h extension.

Including header files from other directories

Another common question involves how to include header files from other directories.

One (bad) way to do this is to include a relative path to the header file you want to include as part of the #include line. For example:

While this will compile (assuming the files exist in those relative directories), the downside of this approach is that it requires you to reflect your directory structure in your code. If you ever update your directory structure, your code won’t work any more.

A better method is to tell your compiler or IDE that you have a bunch of header files in some other location, so that it will look there when it can’t find them in the current directory. This can generally be done by setting an include path or search directory in your IDE project settings.

For Visual Studio users

Right click on your project in the Solution Explorer, and choose Properties, then the VC++ Directories tab. From here, you will see a line called Include Directories. Add the directories you’d like the compiler to search for additional headers there.

For Code::Blocks users

In Code::Blocks, go to the Project menu and select Build Options, then the Search directories tab. Add the directories you’d like the compiler to search for additional headers there.

For GCC/G++ users

Using g++, you can use the -I option to specify an alternate include directory.

The nice thing about this approach is that if you ever change your directory structure, you only have to change a single compiler or IDE setting instead of every code file.

Headers may include other headers

It’s common that a header file will need a declaration or definition that lives in a different header file. Because of this, header files will often #include other header files.

When your code file #includes the first header file, you’ll also get any other header files that the first header file includes (and any header files those include, and so on). These additional header files are sometimes called “transitive includes”, as they’re included implicitly rather than explicitly.

The content of these transitive includes are available for use in your code file. However, you should not rely on the content of headers that are included transitively. The implementation of header files may change over time, or be different across different systems. If that happens, your code may only compile on certain systems, or may compile now but not in the future. This is easily avoided by explicitly including all of the header files the content of your code file requires.

Best practice

Each .cpp file should explicitly #include all of the header files it needs to compile. Do not rely on headers included from other headers.

Unfortunately, there is no easy way to detect when your code file is accidentally relying content of a header file that has been included by another header file.

Header file best practices

Here are a few more recommendations for creating and using header files.

  • Always include header guards (we’ll cover these next lesson).
  • Do not define variables and functions in header files (global constants are an exception -- we’ll cover these later)
  • Give your header files the same name as the source files they’re associated with (e.g. grades.h is paired with grades.cpp).
  • Each header file should have a specific job, and be as independent as possible. For example, you might put all your declarations related to functionality A in A.h and all your declarations related to functionality B in B.h. That way if you only care about A later, you can just include A.h and not get any of the stuff related to B.
  • Be mindful of which headers you need to explicitly include for the functionality that you are using in your code files
  • Every header you write should compile on its own (it should #include every dependency it needs)
  • Only #include what you need (don’t include everything just because you can).
  • Do not #include .cpp files.
  • Order your #includes as follow: your own user-defined headers first, then 3rd party library headers, then standard library headers. This is a minor one, but may help highlight a user-defined header file that doesn’t directly #include everything it needs.

2.12 -- Header guards
2.10 -- Introduction to the preprocessor

503 comments to 2.11 — Header files

  • jamesL

    Hey, your ifndef statement in the header guard is not indented properly, you should always indent your if statements, remember? ;D

    So anyway, I was wondering if there were any simple audio libraries available that you can use in these types of console applications to make chiptune like music. No MIDI libs please, and i'm wanting to create the music myself from written source files so things like libmodplug or game music emu are not what i'm looking for either (though I probably will try those out at some point).Really I just want it to handle the basic stuff like creating the sound buffer, generating the waveform, placing the waveform in said buffer, etc.

    • Alex

      if statements and ifdef/ifndef are two different things.

      For sound stuff, you might check out Simple DirectMedia Layer (SDL).

      • jamesL

        Well I know they are different, one is preprocessor and one is actual program logic :) But I would still write them both the same way anyway.

        Also yeah i have heard good things about SDL. But does it work in the console or does it require a win32 application, because I'm not exactly good enough to make those yet :(

        • Alex

          I think SDL will work with console apps as long as you're not using any of the GUI stuff. But I'm not sure -- I've used SDL a few times but only as a Windows app. My knowledge of Windows apps is super-minimal, but it wasn't difficult to get set up. There are tutorials for such things. :)

  • Ashish


    #ifndef add
    #define add

    int add(int x, int y);



    C:\CBProjects\helloworld\add.h:7:9: error: expected unqualified-id before 'int'
    int add(int x, int y); // function prototype for add.h -- don't forget the semicolon!
    C:\CBProjects\helloworld\add.h:7:9: error: expected ')' before 'int'
    Process terminated with status 1 (0 minute(s), 0 second(s))
    2 error(s), 0 warning(s) (0 minute(s), 0 second(s))

    • Alex

      You're getting a naming conflict between your header guard name and your function name. This is why we typically would use ADD_H for the header guard name, because it won't conflict with anything else.

      • ASHISH

        ITS NOT WORKING still!!

        // This is start of the header guard.  ADD_H can be any unique name.  By convention, we use the name of the header
        #ifndef ADD_H
        #define add

        // This is the content of the .h file, which is where the declarations go
        int add(int a, int b); // function prototype for add.h -- don't forget the semicolon!

        // This is the end of the header guard

  • this is man.cpp, for my header file

    and I pressed on new, then chose the file option and header file to make a header file and I named it man.h

    and then I made a new project called lo and in the main.cpp I added this

    but when I compile it says "fatal error :man.h: No such file or directory."
    I tried using <man.h> instead of "man.h" and I got the same result. Can anyone help me solve this please?

    • Mr. icewiz, please let me, if you still are looking for help, say that your error is that you created a new project just for the main() function. It should live in same project with man.cpp and man.h. I'm sorry for read your message very late. Regards.

    • Dear Mr. icewiz, please let me add that at the end of line

      a semicolon is missed. Our dear Teacher explicitly suggests in a comment:


  • Abheet


    I have a question regarding how header files and cpp files linkup.
    Here it is:

    How does main.cpp search for the add.cpp? I mean, main.cpp knows about add.h, thus main.cpp is sure that add() function exists.
    However how does it find it? Like what is the procedure main.cpp is supposed to follow to look for the add.cpp file?

    Is this how it works? :

    main.cpp: "Alright, add.h told me add() function exists, fine. Now I will just look around and hope that cpp file containing the
    exact code is named the same as add.h (i.e add.cpp)"

    Or is it like this :

    main.cpp: "Alright, add.h told me add() function exists, fine. Now as the only other cpp file linked to me is add.cpp, so that
    must have the code I need!"

    [ What if there are 2 cpp files linked to the main.cpp file? ]

    (A flow diagram would certainly help me! Thanks, again!)

    • Alex

      main.cpp knows nothing about add.cpp. Main.cpp and add.cpp get compiled independently (unaware of each other). It's only at the linker stage that the results of each get combined.

      So it's more like: "compiler: add.h told me add() function exists. I have no idea where, but I'll trust that that is true. linker: I'm going to connect up this call to add() in main.cpp with the definition of add() in add.cpp."

      • Abheet

        Okay that cleared it up a bit!

        So basically the linker hunts for the cpp file containing the definition of add() function and links the found file (add.cpp) to main.cpp right?

        Thanks a lot for quick response!

        • Alex

          Yup, the linker takes all of the object files that the compiler created, links them together, and connects any cross-file references.

  • Alex

    Hi Alex,

    Is it correct to assume that once a header file has so many functions declared inside it, you have to create namespaces for efficiency?

    Many thanks

    • Alex

      No. Namespaces do not add any efficiency. They exist solely for organizational purposes, to help prevent naming collisions.

      The larger your program is, the more benefit you gain from using namespaces. The Google C++ style guide recommends putting all your code in namespaces. This makes sense for a company that does a lot of code sharing. If you're creating your own programs for your own use, namespacing your own code probably isn't necessary.

  • sam

    for people who are using visual studio 2017:
    you can access your project properties by clicking on the "project" tab of top of the screen >> "project name" properties -in my case i see learning2 properties-

    because right clicking on your project in the solution explorer won't get you to the project properties.

  • B1

    hi Alex
    i hope i get answers for my questions ^_^

    1. where is the source code for C++ itself ?!!
    i have search everywhere but no luck

    2. in what language C++ was writing ?!!

    3. can we remove ALL the C libraries & headers from C++ ?
    i want C++ to be 100% pure, can we do that ?!!
    is there someone tried that or something, if so please give me the URL

    thank you

    • Alex

      1) It's not. C++ is distributed as a set of precompiled libraries and header files. You can look at the code in the header files, but not in the precompiled libraries.
      2) Originally, assembly. These days, I'm not sure. It's possible the C++ compiler is written using a previous version of the C++ compiler.
      3) No. Those provide all of the C++ runtimes and standard library.

  • Erik

    Maybe I missed it, but how do you compile the example? "g++ main.cpp" doesn't work, a flag is needed but which one?

  • saurav

    so i was compiling the program without using the header file,just by using function prototype and i got this

    here is my add.cpp

    here is my main.cpp

    and i get this error

    in function 'main'
    undefined reference to 'ad(int, int)
    what seems to be the problem??i have both the files in same project

    • Alex

      Could be one of two things:
      1) Make sure that function add is spelled correctly (your error message says "ad" rather than "add", but this could just be a typo)
      2) Make sure add.cpp is added to your C++ project so that it is compiled in. When you compile your program you should see the compiler compiling it.

  • I'm very pleased to uncover this site. I want to to thank you for your time for
    this wonderful read!! I definitely enjoyed every bit of it
    and I have you book marked to see new things on your web

  • Kiril

    Here is the little Mathematical program i made just to test what have i learned by now.
    What do you think Alex? About the code.




    • Alex

      Function calc() definitely needs a comment indicating what it does. You should also define your variables closer to where you use them rather than at the top of functions.

  • andresmetalowl

    Alex help!
    I could not include it can you explain me why?

    #include <stdafx.h>
    #include <iostream>
    #include <awesome.h>

    void add(int x, int y)
        std::cout << x + y << std::endl;

    int multiply(int x, int y)
        return x * y;

    int main(int x, int y)
        std::cout << awesome() << std::endl;
        std::cin >> x;
        std::cin >> y;
        add(x, y);
        std::cout << multiply(x, y) << std::endl;
        return 0;


    #include "stdafx.h"
    #include "iostream"

    int awesome()
        std::cout << "hello" << std::endl;
        std::cout << "Put 2 numbers please" << std::endl;
        return 0;

    #ifndef AWESOME_H
    #define AWESOME_H

    int awesome();


    • Alex

      If you mean that you awesome.h is failing to be included, the most likely cause is that awesome.h was saved to some directly that your compiler/IDE isn't set up to look for header files in. Make sure you've saved it to the proper directory, or change your include directories to include the directory where awesome.h is living.

  • My dear c++ Teacher, (I mean that),
    Please let me say that in graph (diagram) file add.cpp is compiled in parallel to main.cpp, but as you state in a reply to me, compiler compiles files (and lines) sequentially. Accordingly, given that add.cpp was created AFTER main.cpp should be compiled AFTER it. That's my understanding so far.
    With regards and friendship.

    • Alex

      It is up to the IDE to determine what order to compile files in. Just because add.cpp was created after main.cpp does not mean it will be compiled after main.cpp.

  • manikanth

    what is the difference between <iostream> and namespace std for cout, how they explain the compiler?

    • Alex

      Iostream is a header that contains all the definitions that you need to use input and output routines. Without the iostream header, the compiler doesn't know what std::cout and std::endl are, or how operator<< should work. Including this header allows the compiler to understand what these things are.

      Within the iostream header, all of these definitions are defined inside the std namespace. So to actually access them, you need to use the std:: prefix to access them.

  • I am getting the error "error: ld returned 1 exit status" with the following program:




    I am using Code:Blocks and all the files are associated with the project and set to be Built/linked/and set to debug and release. How can I fix this?

    • Alex

      Are you getting any other error messages?

      • Never mind, I seem to have fixed the issue. For other people reading this comments section, this is my updated main.cpp:

        Also, it's great that you're still following all these comment sections and helping us! And your tutorials are very well written.

  • ritesh tyagi

    hi alex, my question is if the code in the header file is already included in the source file then why we compile the header file?

    • Alex

      I'm not sure I understand the question. Header files are not compiled directly. Instead, they're #included into code files, which copies the contents of the header into the code file, and then the code file is compiled.

      • ritesh tyagi

        thanks a lot Alex for quick reply i am using codeblock....i add the .h file in my project and my code  could not run then i saw  in my .h file properties  that compile option is not checked , i checked then my code ran ok . so this whole scenario led me arise this question , by the way u got it right .and i got the answer as well..the question was do  we need to compile the header files separately???

        • Alex

          No, you should not be compiling your header files separately. They should only be compiled indirectly by being #included into .cpp files, which get compiled.

  • Rafael

    Can any one please help me? Every time that I try to compile my project, the following error
    "1>------ Build started: Project: Maths, Configuration: Debug Win32 ------
    1>  Maths.cpp
    1>c:usersleafadesktopprogrammingmathsmathsmaths.cpp(1): fatal error C1083: Cannot open precompiled header file: 'DebugMaths.pch': No such file or directory
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped =========="

    The code I created are the following:

    [#ifndef MathFunctions_H
    #define MathFunctions_H

    int add(int x, int y)
        return x + y;

    int subtract(int x, int y)
        return x - y;

    int devide(int x, int y)
        return x / y;

    int multiply(int x, int y)
        return x * y;



    [#include "stdafx.h"
    #include <iostream>
    #include "MathFunctions.h"

    using namespace std;

    int main()
        cout << add(3, 4) << endl;
        return 0;

  • Sarah

    #include "stdafx.h"
    #include <iostream>
    #include "add1.h"

    //comments only
    int main()
        std::cout << "Hello World!" << std::endl;

        int x,y;
        //int y;
          x = 12;
           y = 7;
        std::cout << y << std::endl;
        int z;
        std::cout << "Please pick a number" << std::endl;
        std::cin >> z;
        std:: cout << "You entered " << z << std::endl;

        std::cout << "The sum of 3, 4 and 100 is: " << add1(3, 4, 100) << std::endl;
        return 0;

  • Sarah

    Hi, I had created 2 projects one called Function1_4.cpp and one HelloWorld.cpp. In the Function4_1 I have Add1.cpp and Add1.h , test.cpp. In the header Add1.h I have both Add1 and Test initiated. I had add #include "add1.h" in Function4_1.cpp up to this point I have no problem to call both functions (Add1 and test) that was initiated in Add1.h. My problem is I want to call #include "add1.h" in other project HelloWorld  by just adding the path of Add1.h into IDE project settings.

    Error    LNK2019    unresolved external symbol "int __cdecl add1(int,int,int)" (?add1@@YAHHHH@Z) referenced in function _main    HelloWorld    C:\Users\fatima\Documents\HelloWorld\HelloWorld\HelloWorld.obj    1

    • Alex

      If you're going to use function add() from HelloWorld, you need to #include add1.h, AND make sure add1.cpp is added to your HelloWorld project so that the definition for function add() is compiled into the project.

  • Matthew

    Where it says "[h]eader guards prevent a given header file from being #included more than once in the same file", I am not really sure if I am understanding what this means. Does this mean the header guard prevents a file from using "#include add.h" more than once in the same file (main.cpp in this example)? It doesn't make sense to me why one would write the same preprocessor directive more than once in the same file.

    Also, thanks very much for these lessons Alex. I am finding them very helpful for deepening my understanding with the c++ programming language. I hope I can make it to the end eventually.

    • Igna

      You can inlcude more than once header files like this supose you have this files:






      As you can see in the main.cpp you include add.h and double.h and also in double.cpp you include add.h again so if I am not wrong the header guards prevents that a given header is included more than once so there is no a name collision there... I hope that that was the answer you are looking for and sorry about my English but I am Argentinian so I speak Spanish

    • Alex

      > Does this mean the header guard prevents a file from using "#include add.h" more than once in the same file (main.cpp in this example)?

      Close, but no. Header guards prevent the _content_ of a header file from being included more than once in the same file (main.cpp in this example).

      It would be silly to directly #include add.h more than once. But what if you included math.h, and math.h included add.h? Then the contents of add.h would be included twice (once directly, and once through math.h). Header guards prevent this from happening.

  • anony

    not a question, but a remark

    Regarding not putting the relative path of header files, but rather having the compiler know all the paths where to search.

    This is fine for small and medium projects, but in multi-programmer professional projects having hundreds or thousands of files, this approach can become a hindrance since the path is informative. When a programmer is looking at #include declarations it becomes very helpful to know which directory they come from because this not only helps locate the header more easily, but also informs how the .cpp file depends on other parts of the project since the directory structure reflects the project's organization.

    If the directory structure needs to change (beyond simply renaming directories), then there are much bigger issues with the project than having to manually go through and fix the #includes, since this probably means that there were serious problems in the project's design, so there are much bigger changes needed beyond fixing #includes which is rather easy.

  • My dear c++ Teacher,
    Please let me as ask your experienced suggestion on that: I created two Projects with Dev-C++ 5.11 but file main.cpp should be common! so in Project1 I given name for main file: main1.cpp. It works fine! Do you consider this naming okay?
    With regards and friendship.

  • My dear c++ Teacher,
    Please let me express my thanks for reverting article "the" to "a" before "previous lesson". Also let me ask: by saying, "Header guards prevent a given header file from being #included more than once from the same file" do you mean: "in the same file"?
    Also ask: can I think header files as directories in the sense of tree structure?
    With regards and friendship.

  • My dear Teacher,
    Please let me say that under "Writing your own header files" you state: "Now let’s go back to the example we were discussing in the previous lesson. When we left off, we had two files, add.cpp and main.cpp, that looked like this:"
    Actually we were discussing this example in lesson "1.8 — Programs with multiple files". Previous is "1.8a — Naming conflicts and the std namespace".
    With regards and friendship.

  • Matt

    Typo under "Writing your own header files":
    "We’d used a forward declaration so that the compiler would know what add was when compiling main.cpp."

    I think "we'd" should be "we".

  • Eleanor

    I'm a little confused about the how some of the predefined headers work

    I'm using Xcode, and when I create a header file it automatically places #include <stdio.h> at the top of the add.hpp file.
    Specifically, it spits this out:

    I can use it fine when I type my declaration in, it all works great and spits out the program as I'd expect.  

    My understanding is that <stdio.h> works a lot like <iostream> in that it declares certain functions like printf etc. which are useful for the same reason we declare functions like cout, cin, etc.  When I delete "#include <stdio.h>" the program still runs fine, presumably because I'm not using any of the functions it declares.

    I just don't understand why it appears within the header file and not the .cpp file?  Is there any benefit to placing it within the header file?

    Aren't header programs only meant to be used to declare a bunch of functions?  Why would you ever need to include cout, cin, printf, or anything else in the header?

    Thank you so much for these tutorials!

    • Alex

      I honestly don't know why xcode would automatically #include stdio.h in your header files.

      It would make sense for your header to #include stdio.h if your header used anything defined in stdio.h -- but if that's not the case (and it sounds like it's not), then you should remove it.

  • yash

    ive run this programme but have output that graphic.header not found so what to do plz help me out in this urgently rply

    // lots of code removed

  • kanishk

    where am i going wrong?
    the error shows- 1d returned 1 exit status.

  • Marshall H Crenshaw

    I am using Visual Studio Community 2015. I find I am using functions to input and check integers & characters, keep the console window open, asking yes or no to continue, etc. in a lot of projects. I want to put these common functions in a separate folder such as C:\\MHC-CPP, and then add them to my projects when I need them. Build up a little library of common functions I'm using in this tutorial. So this lesson is the first time I've understood how to do this using header files and adding files to my project.

    It took me some time to figure out what to do, so I thought I would post it here in case anyone else needs help.

    First to add the .cpp files to my project:
    On the right hand side of the Microsoft Visual Studio main window is the Solution Explorer frame (unless you moved it somewhere else). Right click on the Source Files folder and choose Add > Existing Item. A file selection window will open. Navigate to where your .cpp file is stored (mine are in C:\MHC-CPP) and select the .cpp file you want to add to your project. Click on Add and your file will be added to your project.

    Next to add the directory for the .h files:
    You want to #include the header file .h (which should contain the function definitions for the .cpp file you added above) into your main project (project.cpp). However you don't want to have to copy the .h files into your project's directory every time you have a new project, as this would defeat the purpose of having a central place to put your own code. So you have to tell the project where the directory is that contains your .h files.
    In the Solution Explorer frame, right click on the project name and choose Properties. The project Property Pages opens. I use Configurations: All Configurations. In the frame to the left select Configuration Properties:C/C++:General. In the frame on the right the top line should be Additional Include Directories. Click on the box to the right and a small down arrow should appear at the end of the line. Click on the arrow and choose <Edit>... A pop-up window opens called Additional Include Directories. Click on the *Folder icon (New Line). Click on the ... at the end of the line and a Select Directory window will open. Navigate to the directory you have your .h files in (in my case C:\MHC-CPP) and choose Select Folder. Click on OK.
    Now when you use #include it will look in the other directory too and find your personal .h files.

    Precompiled headers and stdafx.h
    I've also read that I shouldn't disable the "using precompiled headers" option, since later on with large projects this will be helpful. The problem is with the darn #include "stdafx.h" that VS 2015 requires as the first line in every .cpp source file. Every .cpp file has to have this as the first line. The problem is when the .cpp file is in a different directory than the project, the compiler looks for the "file" in the same directory as the .cpp file. This generates a compiler error because it can't locate the file (a squiggly red line appears under the file name). It doesn't seem to know to look in the project directory. So you have to tell the compiler where to look for that file.
    So repeat the above for the Additional Include Directories, except choose the first directory it opens to, which should be your project directory. Mine is at c:\Users\Marshall\Documents\Visual Studio 2015\Projects\CPP\projectname\projectname. Add this to the additional include directories. Now it works!

    Unfortunately you have to repeat the above process for every new project. But if you change the location of your "libraries" you only have to change it in the Property for the project and not in the individual files.

    Hope this detailed walk-through saves someone some time.

Leave a Comment

Put all code inside code tags: [code]your code here[/code]