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