heap_trouble
heap_trouble

Reputation: 123

Program compiling even though I don't include necessary headers?

So i'm doing some basic OpenGL stuff and for my math functions like vectors, matrices i use the GLM library. I created a header file which is supposed to work with the said library and i noticed it compiles and works as intended without even including the needed headerfiles of the GLM-library.

My simplified example program:

Main.cpp

#include <glm.hpp>
#include <gtc/matrix_transform.hpp>
#include <gtc/type_ptr.hpp>
#include "Header.h"

int main(int argc, char* args[]){
    Header::test();
    return 0;
}

Header.h

#pragma once
#include <iostream>

namespace Header {
    void test() {
        glm::vec3 vec = glm::vec3(1.0f, 5.0f, 1.0f);
        std::cout << vec.x << std::endl;
        std::cout << vec.y << std::endl;
    }
};

My output:

1

5

How is it possible that I don't need to include the GLM-headers in my "Header.h" file?

Upvotes: 2

Views: 509

Answers (3)

Matt Houser
Matt Houser

Reputation: 36073

For C++ programs, the compiler only compiles the .cpp files as a unit. The header files are "included" into the .cpp files.

So the compiler compiles Main.cpp and when the compiler sees #include "Header.h", then it replaces the #include line with the contents of that file.

Because of how this works, the header file does not need to include everything that's needed. This is because it was included by the cpp file before your header file.

Some quirks about this:

  1. If you do #include "Header.h" in another .cpp file that does not have the GLM header files before it, then it will not compile.

  2. If you took the Header.h file and renamed it to a .cpp file, it won't work because then the compiler will attempt to compile it as it's own unit (which will fail because the GLM files are not there).

Upvotes: 3

Kenney
Kenney

Reputation: 9093

You have included the GLM headers already, before you include Header.h.

The compilation unit is your Main.cpp file; header files are not compiled separately.

The C-Preprocessor cpp processes all the # statements before compilation is attempted. Try to run cpp Main.cpp: that will show you the source file that g++ will actually compile.

Upvotes: 2

fuzzything44
fuzzything44

Reputation: 701

.h Files are not compiled. Since you include the glm headers first, when the header.h file is included to the cpp, glm is already included. If you tried to include the header in a separate cpp that didn't have #include <glm.hpp>, it would fail.

Upvotes: 3

Related Questions