Search code examples
c++header-files

How does C++ handle multiple source files?


I'm studying C++ right now, coming from a background in Python, and I'm having some trouble understanding how C++ handles multiple source files. In Python, the import statement first checks the current working directory for the module you're trying to import and then it checks the directories in sys.path. In C++, where would I place a custom made .h file? Where would the compiler even look?

For example, I've got a program, foo.exe compiled from a single source file, foo.cpp, both in the same directory. I decide that I want to organize things a little better, so I create a new .h file, bar.h and dump stuff in there. Would I just need to #include to get to the stuff I put there? What if I want to use bar.h with another program (in a completely different directory)?


Solution

  • There are two include variants:

    #include  "path-spec" 
    #include  <path-spec> 
    

    Quote notation:

    This form instructs the preprocessor to look for include files in the same directory of the file that contains the #include statement, and then in the directories of any files that include (#include) that file.

    The bracket notation looks for header files in certain defined locations.

    With gcc you can get some information about these pathes via:

    $ echo | gcc -v -x c++ -E -
    

    Compilers accept

    -I or /I

    options to add additional pathes.