Search

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:

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

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:

add.h:

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

main.cpp:

add.cpp:

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.

Troubleshooting

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.

Rule

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
Index
2.10 -- Introduction to the preprocessor

500 comments to 2.11 — Header files

  • Louis Cloete

    Two comments:

    1) Under the heading "Troubleshooting:"
    "If you get a compiler error indicating that add.h *wasn't* being found..."

    2) Under "Header file best practices," last bullet:
    Shouldn't it be the other way round? It is done the other way round (stdlib .h's first) in most of the examples.

    • Alex

      1) Fixed.
      2) This is the best practice, though a fairly minor one. Even I have trouble following all the best practices, and there are a lot of examples to update.

      • Louis Cloete

        Regarding 2): Do you have any idea why the style recommendation is that? I am curious. It would make more sense for me to do it the other way around. As you say, though, it is a minor quibble.

        • Alex

          Let's say you had a header file named x.h that needed iostream, but you forgot to #include iostream in that header file.

          If you had a .cpp file with the following include order:

          Things would compile, because the #include of iostream happens before inclusions of the things in x.h that rely on iostream.

          If you do it the other way around (x.h first), the code in x.h will fail to compile, because the iostream dependency hasn't been included yet. Then you can fix x.h to properly include what it needs.

  • Kushal

    I am getting error :

    1>------ Build started: Project: Firstprogram, Configuration: Debug Win32 ------
    1>  stdafx.cpp
    1>  Source.cpp
    1>  Firstprogram.cpp
    1>c:\users\kusingh\documents\visual studio 2012\projects\firstprogram\firstprogram\add.h(7): fatal error C1004: unexpected end-of-file found
    1>  Generating Code...
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

    I have 4 files in my source files :

    1. add .h

    //This is start of header guard. ADD_H can be any unique name. By convention, we use the name of a header file.
    #ifndef ADD_H
    #define ADD_H
    //This is the content of the .h file, which is where the declarations go
    int add(int , int); // function prototype for add.h
    //this is the end of the header guard
    #endif

    2.Firstprogram.cpp

    #include <iostream>
    #include "add.h"
    int main()
    {
        std::cout << "The sum of 3 and 4 is: " << add(3, 4) << std::endl;
        return 0;
    }

    3. Source.cpp

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

    4. Stdafx.cpp

    // stdafx.cpp : source file that includes just the standard includes
    // Firstprogram.pch will be the pre-compiled header
    // stdafx.obj will contain the pre-compiled type information

    #include "stdafx.h"

    // TODO: reference any additional headers you need in STDAFX.H
    // and not in this file

    Not sure what is wrong.

  • Jim

    "Best practice

    A code files should #include its paired header file (even if it’s not strictly needed), as this will in some cases allow the compiler to detect forward declarations with mismatched parameter. types)."

    So, for the example illustrated in the text, should the add.cpp code read

  • Nima

    Dear Alex thank you so much for your excellent tutorials.
    I have some questions about C++ runtime support library which you mention it in this lesson.
    1_Is C++ runtime support library a set of .dll files which is used for building final executable code or it is just static linking?

    2_Where I can find C++ runtime support library files?

    3_How linker knows how C++ runtime support library should be linked in order to make final executable file?
    I know you said that it automatically links to our program but I want to know more about this in C++ runtime support library.

    Thanks in advance!

    • Alex

      1) It depends on the OS. On Windows, they're DLLs which can be statically or dynamically linked into your application.
      2) Again, depends on the OS. They typically install with your compiler. If you're distributing a program, your installer would typically install any runtimes it needs as well, to ensure they exist on the customer's machine. Where your they get installed is compiler/distributable package dependent.
      3) I'm not sure on this one. It's compiler-dependent.

  • R

    I made 2 c++ programs

    1. main.cpp which just has the main function in it

    #include <iostream>
    #include "math.cpp"

    // variable to hold the if statement values
    int s;

    // first and second int variables
    int a;
    int b;

    int main()
    {
        std::cout << "R's simple c++ calc" << std::endl;
        std::cout << "1. Addition" << std::endl << "2. Subtraction" << std::endl << "3. Multiplication" << std::endl << "4. Exit" << std::endl;
        
        std::cin >> s;

        if (s == 4)
        {
            std::cout << "Exiting program" << std::endl;
            return 0;
        }
        
        std::cout << std::endl << "Enter first integer. ";
        std::cin >> a;
        std::cout << std::endl << "Enter second integer. ";
        std::cin >> b;

        if (s == 1)
        {
            std::cout << addition(a, b) << std::endl;
            main();
        }
        
        if (s == 2)
        {
            std::cout << substraction(a, b) << std::endl;
            main();
        }
        
        if (s == 3)
        {
            std::cout << multiplication(a, b) << std::endl;
            main();
        }
        
        return 0;
    }

    and 2. math.cpp which has all the math functions

    int addition(int x, int y)
    {
        return x + y;
    }

    int substraction(int x, int y)
    {
        return x - y;
    }

    int multiplication(int x, int y)
    {
        return x * y;
    }

    Now is my question, why does my program run properly with out including a header file that forward declares the functions.
    or is it because the #include "math.cpp" line implements the code before the main function is called there for already defines the functions.
    If that is the case isn't it more efficient to define your functions in this way?

    thank you in advance

    • Please use code tags next time.
      Don't include .cpp files, you'll end up with duplicate definitions (Which cause an error).
      Your code compiles, because #include copies the contents of the specified file into the current file.

  • Bill Taoqo

    Great Tutorial....
    I am writing program with compiles with armcc which has some prototypes already defined
    But i would like to write and use .cpp files in or otherwise do c++ stuffs..
    But their file structure have things like
    First File is .h (ie.. flyaway.h) and Second file is .c (ie... flyaway.c)
    --flyaway.h--

    --flyaway.c--

    Should i put my cpp code within the extern "C" {cpp code here} in the .h files and call them within the .c files or
    i still need a .cpp extension.. Thanks... Help appreciated

  • Doug

    You might address this elsewhere, but another best practice is to include the header in the file that contains its definitions, which lets the compiler validate the declaration with the definition.  This should be the first include of the file.

  • Mike H

    Hey guys, I got a question for ya.
    I made a quick calculator program using my main function to get the information from the user then I put the "operations" inside a separate calculations.cpp file. When I made the header file, calculations.h, I had

    then I compiled. Things went well until I noticed that when I wrote the code for these declarations I used double x, and double y for my parameters; instead of double a, and double b. Everything compiled fine though. So I went back and just to try it I completely removed the names (identifiers). It still compiled fine. So I ended up with:

    So I'm just wondering; I understand its PROBABLY good practice to include the names(identifiers) in the declarations, but does the compiler even need the names to be able to compile without problems?
    Absolutely amazing tutorials by the way. I've never had a tutorial that was so simple to follow.

    • > its PROBABLY good practice to include the names(identifiers) in the declarations
      Correct. When you use/share libraries, you'll only have/share the headers and compiled source files. Without parameter names in the declarations, the library won't be easy to use.

      > does the compiler even need the names
      No, it doesn't need them.

  • Mateo

    What's the reason to separate the definitions of a header.h into a header.cpp?

    • Alex

      Header files exist to propagate their contents into code files. So a function definition in a header file will get propagated to any code file that #includes that header.

      If two different code files include the same header containing a function definition, now you've got two definitions for the same function in two different code files, which is a violation of the one-definition rule, and will cause an error.

      Placing the function definition in a code file ensures there is only one definition for that function no matter how many times the header (containing a forward declaration) is included.

  • suman

    what it the difference between header file and namespace ?

    • Alex

      Header files are files that are useful for propagating declarations (and some types of definitions) to code files. Namespaces are groupings of identifiers that are used to prevent naming collisions.

  • Lalo

    Hello I was doing the quiz for the first chapter and decide to come back here and I wanted to ask, are header files essentially just a way to facilitate reusing functions in various files? then everything we do with a header file can be done with forward declarations instead right? is the only reason for using header files convenience and organization?

    • Yes.

      > everything we do with a header file can be done with forward declarations instead right?
      Yes, but that'd be extremely inconvenient. Imagine using a function a 20 files and each of those files has a forward declaration of said function. Now you add a parameter to that function. You'll have to update it in 20 different files. Same goes for everything else declared in a header. Headers are just a way to paste a copy of the same code into many different files. So
      > the only reason for using header files [is] convenience and organization

  • Mingrui Zhang

    Hi ALex,
    Just got a little curious about the namespace.
    When the <iostream.h> library is redefined in the std namespace,
    does the implementations are still in the std runtime lib?

    Thank you so much.

  • David

    Hi Alex,

    Thanks for including the "history lesson". It's thoughtful explanations like this that help to demystify a language like C++ for those of us who are coming to it so many years after its inception. Fantastic work you've done on this tutorial, thank you, thank you, thank you!

  • Clapfish

    Hi Alex,

    I've been loving this tutorial so far and really getting into C++ as a result, so thank you for your hard work!

    This is the first lesson where I've come across something that made me wonder, and wasn't really answered in the material (so far as I could see at least), so I thought I'd flag it up.

    When you talk about creating an add.h file, I got slightly lost wondering how best to do that (I'm currently using CodeBlocks). I went through the motions of creating a file like you describe for .cpp files in an earlier lesson, and when it asked whether I want to include it for Compiling and Linking (with check boxes) I wasn't sure what to do. Reading around the topic and some other comments here further, I figured that isn't necessary, and decided to un-check those boxes - indeed the add.h file doesn't appear under my Sources list in the Project like the .cpp files do. As I suspected, everything works fine that way.

    But, it still left me wondering whether that process should be detailed a bit more explicitly, especially since I really appreciate how thorough these lessons have been so far.

    I'd appreciate your thoughts on this!

    All the best, and thanks again.

    • Alex

      In the Management window, make sure that your project is selected. Then in the File menu, choose New > File.... In the New from template dialog that appears, select C/C++ header and click Go. If you get an optional Welcome to the header file wizard dialog, click Next. Now click the ... button underneath the Filename with full path field. In the Select filename file browser that appears, give your header file a name and .h extension. Then click Save. Back on in the C/C++ header wizard dialog, make sure the Add file to active project checkbox is selected, but that the In build target(s) checkboxes are all unselected. Then click Finish.

      I'm in the process of rewriting this lesson, so I'll make sure this gets included in the body of the lesson update.

      • Clapfish

        Hi Alex, thanks for getting back to me!

        That's perfect, just what I felt was missing (so it's great to hear you'll add that to the lesson for future visitors).

        And as you may have noticed, in my haste I made an error mentioning 'Compiling and Linking' in my comment when I meant 'Release and Debug build targets' (unfortunately I couldn't edit the comment when I'd noticed that, so apologies for the inconsistency).

        Best wishes and keep up the excellent work!

  • Shivang

    I have a main file, a definition file and a header. On compiling it gives error - input not found. But the program runs fine. Is there any problem?

  • George

    Followup to my previous comment : I tried changing the header file's name from "division.h" to "divide.h" (goes without saying, i did

    instead in ConsoleApplication1.cpp too). To my surprise, the program linked just fine. Any ideas on why could that be?

  • George

    Ok, so

    Firstly, I made the following header file

    division.h :

    Then made the following program consisting of two files :

    Source.cpp

    ConsoleApplication1.cpp

    When compiling, I'm getting the following errors :

    E0040 : "expected an identifier"    File: division.h   Line: "4"
    E0018 : "expected a ')' "       File: division.h   Line: "4"
    E0065 : "expected a ; "      File: division.h     Line "4"
    C2062 : "type double unexpected"       File : division.h     Line: "4"

    I would really appreciate it if you could enlighten me as to what exactly the problem with my code is. Thank you in advance~

    • Hi George!

      @division is both a preprocessor macro and a function name. The preprocessor macro is defined before the function is declared, so the function cannot be declared. Rename either the header guard or the function.

  • Beginner

    Although it is 2018, I read that using #pragma once is not standard, so I am refraining from using it. When I use the #ifndef, #define, and #endif, I get an error when I include numbers in the name for #ifndef, so I assume when you say "can be any unique name", it means any unique name without numbers? Or is there something I'm missing.

    • Alex

      I'm not aware of any reasons numbers can't be used in preprocessor identifiers. Visual Studio 2017 accepts them, and C++ itself defines several of them.

    • __bs__

      The defined variable can't be _just_ a number or start with a number:

          #define 1 // <- BAD
          #define 1X // <- BAD
          #define X1 // <- OK

      Honestly you shouldn't be afraid of `#pragma once`. There are really two reasons not to:

      a) You are forced to use an ancient (!) compiler.
      b) You are writing code for high performance computing (i.e. supercomputers) and suspect that it might end up on a Cray cluster...

      In both cases you probably know at the start of the project.

  • MorbidPitaya

    Hey!

    Great tutorial! :P
    Concerning the inclusion of header files from other directories...

    Is using the 'Include Directories' in 'VC++ Directories' (in project properties) the same as directly adding existing header files through the 'Source Files > Add > Existing Item...' function? Furthermore, is the former option limited to header files, or can I do the same with .cpp ones as well?

    Lastly, can I have multiple header files (with unique names) have identical header guards (that is, with identical header guard names, such as ADD_H as seen in the example)?

    Looking forward to learning code)

    • Alex

      > Is using the 'Include Directories' in 'VC++ Directories' (in project properties) the same as directly adding existing header files through the 'Source Files > Add > Existing Item...' function?

      No. Adding an include directory tells the IDE to look there for headers. Adding a header through the Existing Item only adds it to the project, which gives you easy access to view/modify it. It doesn't help the compiler locate it.

      > Furthermore, is the former option limited to header files, or can I do the same with .cpp ones as well?

      C++ files need to be added to your project directly.

      > Lastly, can I have multiple header files (with unique names) have identical header guards (that is, with identical header guard names, such as ADD_H as seen in the example)?

      You _can_, but you risk running into problems if you do. If both headers that define ADD_H are #included into the same scope, the second one won't be included because the header guard will prevent it.

  • DonnieDarko

    I copied the exact code you provided and got this error when compiling my AddWithHeader.cpp(main file) file in both CodeBlock and command prompt as well.

    undefined reference to `add(int, int)'
    collect2.exe: error: ld returned 1 exit status

    and when I'm compiling add.cpp, it is asking for main()
    saying

    undefined reference to `WinMain'

    Please guide me where I'm wrong.

    • nascardriver

      Hi DonnieDarko!

      You need to compile both files at the same time. Assuming you're using g++:

      Other compilers should work similar.

      • DonnieDarko

        Thanks a lot it worked.
        But I have a doubt. we import iostream we do not need to compile it every time we run a program but than why we have to compile user defined header file every time we run a program.

        • nascardriver

          You don't need to compile anything every time you run the program. You only need to compile files when you compile the program.
          System files don't need to be compiled, because your OS stores a precompiled versions of them. If you're using an IDE, Make or CMake you only need to compile the files that were modified since the last compilation.
          Here's a basic CMakeLists.txt to get you started:

          • DonnieDarko

            Thank you so much, nascardriver
            Now I'm getting it.
            When I open my old program in IDE I need to "run" it directly rather than "build and run" that means it is precompiled.
            Build == compilation.
            Run == Execution.

          • Hassan

            hi nascar...
            a brief explanation about the "precompiled" thing and description of the code snippet above. please.

            • Hi Hassan!

              There are many functions that ship with c++, which you don't have to write yourself. To use them, you only need their declarations (Their name, their parameters, etc.). The code of the functions themselves has already been compiled (by your OS-maintainer or the relevant package maintainer) and does not need to be compiled again. When you run your program, the program loads the already compiled system files which are required by your program.
              What I posted is a CMakeLists file. It's a config for the CMake system. If you use an IDE, you probably don't need it.

  • Rahul

    Hi Alex, Great Tutorials, Thanku!!
    Is there any android tutorials just like this where i can learn android?

  • hypost

    Great pics!Your tutorials really make my life much easier!

  • Rajsekar

    i named my header file add.h, if i mention this in main like #include "add.h"
    it says "no such file or directory found"...if i see in properties the header name is "../add.h",if i put this name the program compiles but if i use only "add.h" it dosen't...
    someone help me please...I use codeblocks

    • nascardriver

      Hi Rajsekar!

      Sounds like @add.h is in the wrong directory. Make sure it's in the same directory as @main.cpp.

      • Rajsekar

        thank u nascar..i saved that in other directory..now i corrected it, it works fine...

        if i add an empty file and defined functions in that instead of a "source file" it doesn't compile...Y?

  • Me

    I'm having issues with my code (visual studio).
    I have Main.cpp which contains

    I have NewFile.cpp which contains

    and I have NewFile.h which contains

    This is the error I'm getting in the output:
    1>------ Build started: Project: HelloWorld, Configuration: Debug Win32 ------
    1>NewFile.h
    1>Debug\NewFile.obj : warning LNK4042: object specified more than once; extras ignored
    1>HelloWorld.obj : error LNK2019: unresolved external symbol "int __cdecl doubleNumber(int)" (?doubleNumber@@YAHH@Z) referenced in function _main
    1>C:\Users\noahp\source\repos\HelloWorld\Debug\HelloWorld.exe : fatal error LNK1120: 1 unresolved externals
    1>Done building project "HelloWorld.vcxproj" -- FAILED.
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
    What's going wrong here? Thanks.

    • Dima

      Try to add "#pragma once" at the end of "NewFile.h". I've tested your code with this change and it worked.

    • Brian Gaucher

      I think it's because you included a header file inside your header file.

      Main.cpp

      Newfile.h

      You end up include'ing' "stafx.h" twice which is redundant. So it warns you

  • himanshu

    HI Alex!
    Here i need your help please reply.
    I totally confused what we do after
    creating a directory.
    for example you created a directory using g++
    and then what !
    what is the uses of this directory.

    • nascardriver

      Hi himanshu!

      g++ doesn't create a directory, you create it and tell g++ where it is.

      This directory contains header files which you can then include from your other files.

      main.cpp

      [../src/source/] g++ -I ../includes/ apple.cpp main.cpp

      The "-I ../includes/" allows all files to include files that are located in src/includes/.

      • himanshu

        hi
        i does not understand what  you are try to say
        but can we create our own directory

        • Alex

          You can, but you don't need to. And unless you have a specific reason to do so, you probably shouldn't. :)

          • himanshu

            Hi!
            Alex

            GOOD MORNING!

            I think you had explained to how to create our own directory.

            But please answer my this question as simple as you can.

            I totally confused what we do after
            creating a directory.
            for example you created a directory using g++ and then how can we call it or its components that it contains.

            AND ONE BONUS QUESTION:

            Difference between header file and directory.

            • Alex

              I don't explain how to create a directory anywhere (how to do so depends on your operating system, not g++). The directories mentioned in the g++ example are using directories that have already been created, not creating them.

              A header file is a C++ file that contains declarations. A directory is a container that is part of a heirarchical file system. See https://www.computerhope.com/jargon/d/director.htm

  • Ishak

    #include <iostream.h> does this include the function definition? I'm confused. what did they move from <iosteam.h> to std namespace that made <iostream.h> not usable? why couldnt they use namespace std on old programs??

    • Ishak

      Also C++ runtime support library, is that namespace std? or am I confusing stuff?

    • Alex

      > #include does this include the function definition?

      Typically not, the definitions are typically only provided as a precompiled library file, which gets linked into your program.

      > what did they move from to std namespace that made not usable?

      All of the declarations were moved from outside the std namespace to inside the standard namespace. This means any code using iostream.h would not work with iostream, as the code doesn't use the std:: prefix as required to access those declarations inside the namespace.

      > why couldnt they use namespace std on old programs??

      You could, but the point of the name change was to make it so you could still compile older programs without having to modify them first.

  • Hema

    In the above example of add.h, add.cpp and main.cpp, is the scope X and Y restricted to add.cpp or are they accessible in main.cpp also?

    • nascardriver

      Hi Hema!

      @x and @y are parameters of @add. They are set by the caller and can only be accessed by @add.
      In the above example @x will be set to 3 and @y will be set to 4, after that only @add can read and change those variables. They disappear when @add returns.
      Function parameters are covered in lesson 1.4a.

  • omar

    hello
    my question what is the main function of header file #include "stdafx.h" ...why we use it? is there any alternative way for it?

  • nascardriver

    Hi Alex!

    I ran into something here and I'm confused whether this is a feature of C++ or a compiler problem.

    other.hpp

    main.cpp

    Now, naturally I'd say this doesn't work. The syntax is all messed up. But it does work. I understand why it works but I can't imagine it's supposed to.
    Tested with g++ and msvc++.
    Removing the closing bracket in main.cpp will cause a compiler error in main.cpp when using g++ or in other.hpp when using msvc++.
    I didn't test things other than a namespace, I guess they behave the same.
    Please tell me this isn't legal C++.

    • Alex

      It's syntactically legal, though rather idiotic. :) Header files don't get compiled directly, they only get compiled when they are included into a .cpp file. So when main.cpp #includes other.hpp, the contents of other.hpp are copied into main.cpp at the point of inclusion (by the preprocessor). Then _that_ is compiled. The compiler has no idea that the closing brace in main.cpp was ever disconnected from the namespace in other.hpp...

      That said, you should never do this. :)

Leave a Comment

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