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.

Key insight

Header files allow us to put declarations in one location and then import them wherever we need them. This can save a lot of typing in multi-file programs.

Using standard library header files

Consider the following program:

This program prints “Hello, world!” to the console using std::cout. However, this program never provided 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 preprocessor processes 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 suffix. 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 file should explicitly #include all of the header files it needs to compile. Do not rely on headers included transitively 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.

Q: I didn't include <someheader.h> and my program worked anyway! Why?

This is one of the most commonly asked questions on this site. The answer is likely because you included some other header (e.g. <iostream.h>), which itself included <someheader.h>. Although your program will compile, Per the best practice above, you should not rely on this.

The #include order of header files

If your header files are written properly and #include everything they need, the order of inclusion shouldn’t matter. However, including your header files in a certain order can help surface mistakes where your header files may not include everything they need.

Best practice

Order your #includes as follow: your own user-defined headers first, then 3rd party library headers, then standard library headers, with the headers in each section sorted alphabetically.

That way, if one of your user-defined headers is missing an #include for a 3rd party library or standard library header, it’s more likely to cause a compile error so you can fix it.

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.

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

560 comments to 2.11 — Header files

  • Helliarc

    Coming back from future lessons is incredible, but I noticed there's a struggle in the "why header files and includes", and I'm trying to wrap my head around this myself. What I gather, using what's been taught so far, is that separate header files provide organized functionalities, so you have add.h/add.cpp, subtract.h/subtract.cpp... expand this capability and you'll have potentially hundreds of .h/.cpp files, which is actually desired, otherwise you'll have THOUSANDS of forward declarations and function definitions in your main.cpp file. (Better handling of your .h/.cpp coding will lower the amount of .h/.cpp files, but that comes with time and practice with consolidation of code)

    Now here's where it's tricky, the "#include "xxx.h" tells the compiler that the function declarations for the functions you want to use exist in the project, so build it. Then the linker finds those function definitions, and builds it. The compiler is building the .cpp files, all separately, so you need to include the .h associated with the cpp files being built, the linker connects all the separate files, the compiler just verifies the syntax. The linker needs to know THIS functions definition, to do the work, and it's told where to find it, by following the instructions of the .h, which forward declares the functions exist. This provides greater organization capability, modularity of code, and prevents functions that are defined in .cpp files from taking up space when they aren't necessary for the compiled project, but exist anyways in case you need them later.

    One thing that eluded me for the longest time, is that you can write functions and never use them. You do this in separate files, because if you define a useless function in main, main will HAVE to call it, because main scripts through the list of instructions. You can have 10000 functions defined, in another file (cstdlib), and never call any of them or use them in your program. But if you want to use one, just #include, and you now have access to use them. The linker only cares about the functions in that #include that you call through main(), the rest are ignored and irrelevant. Then you add classes and inheritance, some operator overloading, and function parameters/arguments, and your head explodes!

  • tbrowne03

    Hi there,

    Quick naming convention question. Why are we naming our header file add.h, rather than main.h ? Say we wanted to forward declare add(), multiply(), and divide(). Wouldn't it be better to include all these declarations in one header file called main.h rather than three separate header files?

    Thanks.

    • nascardriver

      Those should go in a header called "math.h" or similar and their definitions in "math.cpp".
      Since we only have 1 function, there's nothing wrong with naming the header identical to the function.

  • Humam

    nascardriver, could you please kindly provide another beginner-level example on why we included the header file in the add.cpp as well? Some statements are a bit advanced from where I'm at (strictly following the chapters here). I tried to pick the point of why we added it but I failed.

    From what I understood from your code, you declared mew in cat.hpp as a const char that returns nothing.
    Then we decided it needs to return something in the definition in cat.cpp, but we didn't update our declaration.
    We included cat.hpp in our main program, it will look at the declaration that returns nothing, and not find a definition (Because we called it, it will trigger the linker error).
    We included cat.hpp in our cat.cpp code, but it will not match, giving a compiler error.
    But if we change the parameters and type, it will succeed (Obviously).

    But why did we include add.h in our add.cpp? Isn't that considered redeclaration? Which then opened my eye on one thing which I did and it mysteriously (From my beginner level) worked fine.

    ------------------------------------------

    #include <iostream>

    void displayText();
    void displayText();

    void displayText()
    {
       std::cout << "Hello.\n";
    }

    int main()
    {
       displayText();
       return 0;
    }

    ------------------------------------------

    The code above worked, no compiler error was given, I understand if there was no reason to, but which declaration is being used right now? The first one or the second one? Is it safe to assume that the first one got overwritten by the second one? and that our redeclaration is just considered redundant? I'd like to understand the purpose of including the header file in the add.cpp file and why it is not considered redundant.

    P.S.

    didn't work with me :( Maybe because it's a reply rather than a new comment.

    • nascardriver

      I moved your comment to the top so I can reply, there were too many replies already.

      > From what I understood from your code
      What you said is correct. We include "add.h" in "add.cpp" for the same reason, to catch error early.

      > Isn't that considered redeclaration?
      We can declare functions as many times as we like. You just can't define a function more than once.

      > which declaration is being used right now?
      It doesn't matter, because they're the same. I suppose your compiler ignores the second declaration.

      > P.S.
      Code tags don't get displayed after you edit a comment. Refreshing the page fixes them.

  • zuhail

    Hey short question related to namespace ?
    i created a namespace in a header file in my project and i only declared every identifier in the namespace,
    giving definitions of each identifier belonging to that namespace in a different .CPP file(with the same namespace as the header file) and then my project(codeblocks) worked well is this a correct approach?
    and should namespace always need to be created in a header file?

  • Chayim

    What can user defined header files do what defined and declared functions cannot? Why do I need user defined header files? In the example header given here, declarations and definitions can be used instead of headers. Did not get the purpose and details on what to use user defined header files.

    • nascardriver

      If you need a function in several other files, you'd have to manually declare the function everywhere. When you update the function, you have to update its declaration in every other file as well. With header files, you write the declaration only once and include the header wherever you need it.

  • Aryaman Karde

    One simple question to @nascardriver & @alex is , from where did you learned all this ?

    • nascardriver

      I learned the programming basics in other languages. I switched to cpp with the help of videos. Then I wrote code until I got errors or didn't know how to solve a problem. Whenever that happened, I googled for solutions.
      After that, I looked through standard library references and stayed in touch with standard updates.

    • Alex

      For me, I learned C++ in college, which introduced me to the fundamentals (pre-C++11). I spent many years working professionally as a developer (also pre-C++11). And although I no longer do that, I still work with developers, occasionally code as a hobby, and read a lot to try to keep up to speed on the latest standards.

  • Renan

    On section "Writing your own header files", the fisrt line of code of the file add.cpp, is: #include "add.h", but it should be: #include <iostream> instead, isn't it?

    • nascardriver

      No, "add.cpp" doesn't use anything from , so it shouldn't include it.
      It also doesn't use anything from "add.h", but including the corresponding header can help finding errors more quickly.

  • Justin

    What do you mean by 3rd party header files. What's the difference between those and "standard" ones.

  • Mike

    What is the meaning of 'o' in regards to main.o and add.o? I've noticed it a few times now referenced in some of the images, though I don't recall it being discussed. I apologize if is has been.

  • Nguyen

    Hi

    Why do we need to #include "add.h" in add.cpp in the last example?

    Thanks

  • Steve Smith

    "this program never provide a definition" should be "this program never provided a definition".  

    Great tutorial though!

  • daniel

    Is their a simple explanation why "add.h" is also put into "add.cpp" ?

    When your calling a function thats in a different location without a header file you normally add an function prototype correct? And you normally dont add a function prototype to where the function code is correct? so why do you add the add.h to the add.cpp file when your using the header files?

    for example

    hopefully that makes sense^ i couldnt seperate the code useing the [code tings so imagine that the caller file is seperate to the add file

    • See my comment here
      https://www.learncpp.com/cpp-tutorial/header-files/comment-page-8/#comment-413858
      or here
      https://www.learncpp.com/cpp-tutorial/header-files/comment-page-8/#comment-398571

      • daniel

        so if i understand correctly you add the header file to the code file so if you change the function signature in the code file without also applying the same change in the header file the compiler would detect that the header file function prototype signature is different compared to the one with the same identifier and then the compiler emits an error so the user knows the issue?? correct?

  • Kelen Kell

    Can you explan more about this statement?
    "Be mindful of which headers you need to explicitly include for the functionality that you are using in your code files."

  • Piyush Pranjal

    Typo error

    a .h stuffix == suffix

  • yesyes

    "When the compiler compiles the #include "add.h" line, it copies the contents of add.h into the current file at that point."

    Why is compiler performing that task? Shoudn't it be a preprocessor? Isn't purpose of preprocessor to look for directives and paste the content of included file?

  • Samovar

    When I created FunctProto.h, 3 macros if conditionals are automatically written as shown below:

    #ifndef FUNCTPROTO_INCLUDED
    #define FUNCTPROTO_INCLUDED

    #endif // FUNCTPROTO_INCLUDED

    int Nabe(int N, int B);

    When I run main.cpp, the error reads "function definition is not allowed here.

    Please advise.

    • Remove them for now, they're covered later.
      If you receive an error, post your full code and error message.

    • Samovar

      As you instructed, I removed those automatically written header guard in FunctProto.h the following:

      So in FunctProto.h, it only has:

      So I run my only 2 files, my main.cpp and FunctProto.h,:

      However, the error still reads 'function definition is not allowed here.'

      Please advise again.

      Thank you for your patience and prompt guidance.

  • kaijung

    I don't see the point of adding a header file, is it for scaling/readability purposes?

    Doesn't the add.cpp do just fine in storing all the function declarations?

    • If you're using someone else's code, you don't need to know how their functions work, you just want to know how to use them. Headers show you what you need to know without making you read through lots of definitions.

  • Samira Ferdi

    Hi Alex and Nascardriver!

    I'm still don't understand what is the point of including add.h in add.cpp. Why you do that? I'm trying to understand the Nascardriver cat's (cat.hpp and cat.cpp) example and I just don't get it.

    • Most often the source file needs some entities that were declared in the corresponding header, you won't encounter a situation in which you don't have to include the header very often.
      For executables, it doesn't matter whether or not you include the header, other than that your editor might provide better auto-complete if you do include the header.
      In libraries, it can be helpful. Libraries don't have an entry point (`main` function), since they don't do anything on their own. There will be functions in the library that you offer someone else to use, but don't use yourself.
      Consider this cute fox

      fox.hpp

      fox.cpp

      We're not calling `wagTail` ourselves, we wrote it so someone else can use it.
      `wagTail` has the same signature in both files, everything is fine.
      Suddenly you want to let the end-user decide if the fox should wag its tail now or do it later.
      You change fox.cpp to

      But you forget to update fox.hpp.
      The important part is that `wagTail` now has a different return type. It compiles fine, since the declaration and definition aren't checked against each other. It also links fine, because you're not calling the function anywhere.
      If the user of the library tries to call `wagTail` as it is defined in fox.hpp, the linker won't find a definition for it and error out.
      If we had included fox.hpp in fox.cpp, the compiler would've detected that there are two different versions of the same function, because now they're in the same file.

      • Samira Ferdi

        I've tried your code, so in my fox.cpp is like this:

        and my fox.h is like this:

        I have two issues here:

        1. If I compile my fox.cpp above individually, the compiler throw an error that sounds "ambiguating the new declaration

        with the old declaration

        ". So, instead of my compiler detect "Oh, there are two different functions regardless I write the

        definition in fox.cpp or not", the compiler is confuse now because ambiguity. The same thing happen if I call wagTail(3)

        I undestand that the ambiguity is I write same identifer with different data type (this issue I point out in my second issue). I don't know if your compiler or compiler setting is little bit different than what I use - I use CodeBlocks 16.01 with its default compiler settings.

        2. The second issue is catch my eyes. So, in fox.h is still the same like above but in my fox.cpp I don't #include fox.h in my fox.cpp and I don't write the definition of

        . So, my fox.cpp now is

        and my main.cpp is

        I try to run my program, and the wagTail(3) definition that being called is

        but in the fox.h is

        . This is confuse me. But if I call wagTail(3) in main.cpp like this

        , the compiler throw errors that the point is "The compiler doesn't know to convert the argument 1 to void".

        I hope you can solve my issues. Thanks

        • 1.
          That's the expected behavior. You're including fox.hpp in fox.cpp, so the compiler notices the difference in the 2 functions.

          2.

          main.cpp only sees the declaration of `wagTail`. The declaration still says that `wagTail` doesn't return anything (`void`). `void` can't be printed, so the compiler aborts compilation.
          If you remove the `std::cout <<` and just leave `wagTail(3);`, the program shouldn't link, because there is no definition of `void wagTail(int)`.

          • Samira Ferdi

            Thanks for reply!

            I still don't see the point of including add.h into add.cpp or fox.h into fox.cpp. If, we change the fox.cpp, we can just change the fox.h and there is no problem anymore.

            If we had included fox.hpp in fox.cpp, the compiler would've detected that there are two different versions of the same function, because now they're in the same file. This cause the compilation is abort. If, the compiler would've detected that there are two different versions of the same function, so, what? What is the next step or the solution? The compiler is abort anyway. Is including fox.h into fox.cpp just an alert to the programmer that "you change the fox.cpp but you forget to change the fox.h" or "hei, there are two versions of the same function (same identifier but different type), are you sure these are correct"?

            • > Is including fox.h into fox.cpp just an alert to the programmer that "you change the fox.cpp but you forget to change the fox.h"
              Yes. It only helps you to notice that you forgot to update 1 file after modifying the other. If you don't notice this, your clients/coworkers/internet will notice and they'll be unable to use your library (Or the affected function at least).

  • v5l

    Hello,

    when I create a header file in visual studio,

    is automatically written at the top of the file.
    What does it does ? Do I need to get rid of it or is it better to leave it there ?

    Excellent tutorial by the way.

  • Stephen

    So I've followed the tutorial word for word in the code so far.

    #include "add.h" works perfectly in the main.cpp; however, add.cpp throws an exception saying no such file/directory.

    Both .cpp files are in the same source file within the solution
    add.h is in the Header Files location.

    I'm using VS 2019 Community

    main.cpp:

    #include <iostream>
    #include "add.h"

    int main()
    {
        std::cout << "The sum of 3 and 4 is: " << add(3, 4) << "\n";
        return 0;
    }

    add.cpp:

    #include <iostream>
    #include "add.h"

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

    add.h:

    int add(int x, int y);

    EDIT: Sorry, I don't know how to wrap in code block properly

    • Stephen

      I've figured out where I was going wrong.

      In previous lesssons, dealing with multiple files, I created a new project for the add.cpp file; then added the file into my main.cpp project; so it was looking for add.h in its original project directory.

      I've now deleted that file from my main.cpp project and just created a cpp file called add, that looks in the right header files directory

  • /**/

    Hey, what's the reason behind including the add header (add.h) in add.cpp?

  • Red Lightning

    "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"

    But in the previous lesson it was said that the preprocessor is responsible for the #includes, as they are preprocessor directives. Where is the mistake? What am I not understanding?

    • Alex

      The mistake is in my sentence -- I said "compiler" when I meant "preprocessor". I've updated the lesson. Thanks for pointing out the inaccuracy.

  • Shrushti Vora

    Hi,
    When creating a header file as a class declaration file, should we always declare variables with keyword extern followed by a type specifier?

  • Juan

    I keep learning new things in this tutorial! As the difference between the headers with h and without it. Thanks

  • 5n1p3r_4rt3m1s

    "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)." ??? I cant understand this..

    • Alex

      I'm having a hard time finding a good example of this. I'm going to back the recommendation off a bit until I can find a better use case that illustrates why.

      • Although a rare encounter when writing programs, this is relevant when writing libraries.
        Not all functions are used, so the linker won't try to find function definitions.

        cat.hpp

        cat.cpp

        If we were writing a program, we might have a main.cpp

        The linker will abort, alerting us that no definition of @mew exists.
        Though, with libraries, we don't call all of the functions we write, we just offer them for other programmers to use.
        If we didn't call @mew from anywhere, the code would compile and link fine.
        By including @"cat.hpp" in @"cat.cpp"

        the compiler will error out, because there are 2 function declaration that only differ in their return type, which is illegal.

        Granted, compilation and linkage will succeed if the function parameters differ.
        ld has an option to disallow undefined symbols, that helps too.
        A 1-liner to avoid mistakes like this is worth a mention.

  • 5n1p3r_4rt3m1s

    "%Failed lesson reference, id 7938%" in Writing your own header files section. Seems like some error in this webpage's code.

  • Hadi

    Hi ALEX
    You said that iostream.h is a different header than iostream
    then why in Code::Blocks if i tried to #include<iostream.h>
    i get the error message ..No such file or directory..
    thank you so much for this great website..

    • Alex

      Because iostream.h is deprecated, and was deprecated so long ago that many compilers don't even provide a version of it any longer.

  • jih332

    Hi there,  
      
    I was practicing on problem 6.x.2), I wrote a main.cpp in current directory, and wanted to reuse some code in another directory ../lib (safe_input.h, safe_input.cpp, sort.h, sort.cpp to be specific). so I included both "safe_input.h" and "sort.h" in main.cpp, and compiled it with

    but it said

    then I changed it to

    it started to compile, but still complained that

    so how should I write compiler command in this situation? (p.s. I checked the solution for this problem, and found that it also gave the same [-Werror=effc++] error as mentioned above).
    Thanks!

  • Kol

    Please help! I'm using Atom and my code wont work unless I use #include "add.cpp" (Is this a setting I have to change?)
    Here is the code for all 3 files:

    //add.cpp  
    #include "add.h"
    int add(int x, int y)
    {
      return x + y ;
    }

    // add.h
    int add(int x, int y);

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

  • James III

    Can anyone help me? I'm using Microsoft Visual Studio community. Is there a way to create another version of a project that is already created, along with the rest of the project so the solution explorer of the new version is the same as the original version?

    I have an application that is 1263 lines long that I wrote and everything in it works fine. Now I'd like to recreate this whole project so I can make major changes to modify the behavior of the original app without effecting the original app so as to evolve the app to be more advanced than the original.

    The original app is a Windows Console Application and has an #include "stdafx.h". Every time I create a new Windows Console Application project, it always #includes "pch.h" and if I add #include "stdafx.h", I get an error that it cannot be opened.

    If anyone can help me with this, it would be greatly appreciated. If you need more info, please let me know. Thank you very much.

    • stdafx.h has been replaced with pc.h
      I don't know about your other question

      • JamesIII

        Thank you nascardriver for getting back to me. If pch.h replaces stdafx.h, then I have to try and redo my code with the new #include.

        My program using #include "stdafx.h", the reading from a text file works fine. This program does all it's supposed to do. I have a menu with 11 selections to it that all do different things that count on the data in my text file. Everything works fine.

        Now I continue on creating a new project that has #include "pch.h" automatically added in, copying the main() function only from the old program and pasting it to the new program, the program compiles, but the reading from the text file no longer functions. Reading out the file output (using std::cout << ...) produces only blanks and when I get to the part where I use stoi to convert a string to an int, the program aborts.

        I'm sorry, but I cannot for the life of me figure out how to remedy this. Is there another header file I should be including to get the file reading working again in the new program? I'm already including <fstream>, <iostream>, <string>, "stdio.h" and <cmath> along with "pch.h". If I take the pch.h out, the program won't compile. If I include "stdafx.h", I get an error   "cannot open source file stdafx.h", but this file also isn't in the solution explorer. If I add it to the solution explorer, duplicating what I have with the old program, and try and compile, I get the following:

        1>------ Build started: Project: NewMain, Configuration: Debug Win32 ------
        1>NewMain.obj : error LNK2011: precompiled object not linked in; image may not run
        1>C:\Users\JamesIII\source\repos\NewMain\Debug\NewMain.exe : fatal error LNK1120: 1 unresolved externals
        1>Done building project "NewMain.vcxproj" -- FAILED.
        ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

        I'd really appreciate it if someone could help me out so I can see what I'm doing wrong. I can't see why file reading stops working with "pch.h". If you need any more info, please let me know. Thank you for considering my dilemma.

        • Disable precompiled headers in your project settings and remove the includes to @"stdafx.h" and @"pc.h". Those file are just some VS junk that you don't need. It causes more problems than it's helpful.
          You have 1 unresolved external (ie. a function in a library that cannot be found).
          I can only guess that this is caused by the precompiled headers and should be resolved by disabling them. If it doesn't, leave another comment with a minimal compilable code example that causes your problem.

          • JamesIII

            Hello Nascardriver, I solved that problem I've been having. It's not with pch.h or stdafx.h, but has to do with the placement of the data file I'm using with the program. Placing a copy of the data file in the same directory as the new program (with #include "pch.h") and giving it a new name like changing "afile.dat" to "tfile.dat", the program works just like the original program. I'd like to apologize for drawing your attention to a problem that was more of an oversight on my part, but also thank you very much for getting back to me.

Leave a Comment

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