c++visual-studioprojects-and-solutions

How to #include header files from other projects from the same solution


I am working on a game using Visual C++. I have some components in separate projects, and have set the project dependencies. How do I #include a header file from a different project? I have no idea how to use classes from one project in another.


Solution

  • Settings for compiler

    In the project where you want to #include the header file from another project, you will need to add the path of the header file into the Additional Include Directories section in the project configuration.

    To access the project configuration:

    1. Right-click on the project, and select Properties.
    2. Select Configuration Properties -> C/C++ -> General.
    3. Set the path under Additional Include Directories.

    How to include

    To include the header file, simply write the following in your code:

    #include "filename.h"
    

    Note that you don't need to specify the path here, because you include the directory in the Additional Include Directories already, so Visual Studio will know where to look for it.

    If you don't want to add every header file location in the project settings, you could just include a directory up to a point, and then #include relative to that point:

    // In project settings
    Additional Include Directories    ..\..\libroot
    
    // In code
    #include "lib1/lib1.h"    // path is relative to libroot
    #include "lib2/lib2.h"    // path is relative to libroot
    

    Setting for linker

    If using static libraries (i.e. .lib file), you will also need to add the library to the linker input, so that at linkage time the symbols can be linked against (otherwise you'll get an unresolved symbol).

    Adding another project as a reference will add it to linker input (Project Properties -> Linker -> Input -> Additional Dependencies). To add a reference:

    1. In Solution Explorer under your project there is a References node. Right-click on it, and choose Add Reference...
    2. Select another project, and click OK.

    Now building your project will trigger building another project if necessary, and the linker will be able to resolve external symbols.