Search

1.9 — Header files

Headers, and their purpose

As programs grow larger and larger (and include more files), it becomes increasingly tedious to have to forward declare every function you want to use that lives in a different file. Wouldn’t it be nice if you could put all your declarations in one place?

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, sometimes known as an include file. Header files usually have a .h extension, but you will sometimes see them with a .hpp extension or no extension at all. The purpose of a header file is to hold declarations for other files to use.

Using standard library header files

Consider the following program:

This program prints “Hello, world!” to the console using cout. However, this program never defines cout, so how does the compiler know what cout is? The answer is that cout has been declared in a header file called “iostream”. When we use the line #include <iostream>, we’re requesting that all of the content from the header file named “iostream” be copied into the including file. That makes the content from the header file available for use in our code file.

Keep in mind that header files typically only contain declarations. They do not define how something is implemented. So if cout is only declared in the “iostream” header file, where is it actually defined? It is implemented in the C++ runtime support library, which is automatically linked into your program during the link phase.

Consider what would happen if the iostream header did not exist. Wherever you used std::cout, you would have to manually copy in all of the declarations related to std::cout into the top of each file that used it! This would require knowledge of what’s relevant and what’s not. It’s much easier to just #include iostream!

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:

add.cpp:

main.cpp:

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

We used a forward declaration so that the compiler would know what “add” was when compiling main.cpp. As previously mentioned, writing forward declarations for every function you want to use that lives in another file can get tedious quickly.

Header files can relieve us of this burden. A header file only has to be written once, and it can be included in as many files as needed. This also helps with maintenance by minimizing the number of changes that need to be made if a function prototype ever changes (eg. by adding a new parameter).

Writing our own header files is surprisingly easy. Header files consist of two parts.

The first part is called a header guard, which is discussed in the next lesson (on the preprocessor). Header guards prevent a given header file from being #included more than once in the same file.

The second part is the actual content of the .h file, which should be the declarations for all of the functions we want other files to be able to see. Our header files should all have a .h extension, so we’ll call our new header file add.h:

add.h:

In order to use this header file in main.cpp, we have to include it.

main.cpp that includes add.h:

add.cpp stays the same:

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 function prototype for add(), this prototype is now being used as a forward declaration of add()!

Consequently, our program will compile and link correctly.

Note: When you #include a file, the entire content of the included file is inserted at the point of inclusion.

If you get a compiler error about add.h not being 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”.

If you get a linker error about add() not being defined, make sure you’ve included add.cpp in your project so it compiles properly!

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 compiler 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 compiler that this is a 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.

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

Header files may include other header files. However, you should never rely on this. Always #include all of the header files you need to use from each .cpp file.

Rule: Each .cpp file should explicitly #include all of the header files it needs to compile.

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, because iostream.h is a different header file than iostream is! To explain requires a very short history lesson.

When C++ was first created, all of the files in the standard runtime library ended in .h. Life was consistent, and it was good. The original version of cout and cin lived in iostream.h. When the language was standardized by the ANSI committee, they decided to move all of the functions in the runtime library into the std namespace (which is generally a good idea). However, this presented a problem: if they moved all the functions into the std namespace, none of the old programs would work any more!

To try to get around this issue and provide backwards compatibility for older programs, 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>.

When you include a header file from the standard library, make sure you use the non .h version if it exists. Otherwise you will be using a deprecated version of the header that is no longer supported.

In addition, many of the libraries inherited from C that were 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.

However, when you write your own header files, you should give them all a .h extension, since you will not be putting your code in the std namespace.

Rule: use the non .h version of a library if it exists, and access the functionality through the std namespace. If the non .h version does not exist, or you are creating your own headers, use the .h version

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:

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.

In Visual Studio, you can 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 your include directories there.

In Code::Blocks, go to the Project menu and select “Build Options”, then the “Search directories” tab. Add your include directories there.

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.

Can I put function or variable definitions in a header file?

You shouldn’t, as it may cause linker errors. We’ll explain why in the upcoming lesson on header guards.

Declarations are okay.

Header file best practices

Here are a few best practices for creating your own header files.

  • Always include header guards.
  • Do not define variables in header files unless they are constants. Header files should generally only be used for declarations.
  • Do not define functions in header files.
  • 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.
  • Give your header files the same name as the source files they’re associated with (e.g. grades.h goes with grades.cpp).
  • Try to minimize the number of other header files you #include in your header files. Only #include what is necessary.
  • Do not #include .cpp files.
1.10 -- A first look at the preprocessor
Index
1.8a -- Naming conflicts and the std namespace

355 comments to 1.9 — 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

    I FORMED THE HEADER FILE SOMETHING LIKE THIS UNDER "add.h"

    #ifndef add
    #define add

    int add(int x, int y);

    #endif

    WHEN I TRIED TO BUILD IT SHOWS SOMETHING LIKE THIS

    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!!
        WHAT’S THE PROBLEM WITH MY CODE??

        // 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
        #endif

  • 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?

  • Abheet

    Hello!

    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
    site.

  • 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.

    main.cpp

    calc.cpp

    calc.h

    • 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?
    main.cpp:

    #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;
    }

    hello.cpp:

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

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

    awesome.h
    [code
    #ifndef AWESOME_H
    #define AWESOME_H

    int awesome();

    #endif

    • 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:

    main.cpp

    multiply.cpp

    math_functions.h

    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 ….as 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:
    "MathFunctions.h"

    [#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;
    }

    #endif]

    Maths.cpp

    [#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:

      main.cpp

      add.h

      add.cpp

      double.h

      double.cpp

      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
    #include<iostream.h>
    #include<conio.h>
    #include<dos.h>
    #include<graphics.h>
    #include<stdio.h>
    #include<stdlib.h>

    // 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 C++ code inside [code][/code] tags to use the syntax highlighter