Search code examples
c++compilationlinkerinclude

How does Visual Studio compile together multiple C++ files?


I have a simple project in visual studio with main.cpp, Log.cpp, and Log.h.

main.cpp:

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

int main()
{
    Log("Hello World");
    std::cin.get();
}

Log.cpp

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

void Log(std::string message)
{
    std::cout << message << std::endl;
}

void InitLog()
{
    Log("Initialized Logger");
}

Log.h:

#pragma once
#include <string>

void Log(std::string);
void InitLog();

I know that the #include statement copy-pastes all of the included file's code into the file where it's written. My question is that how is it that when I run this, the function Log runs as expected?

We are including the Log.h file from both main.cpp and Log.cpp, but that's just the function declaration. We never include Log.cpp in main.cpp, so how does main.cpp get the function body of Log()?


Solution

  • This is known as the process of linking. The compiler needs to know the return types and signatures of the functions in the Log class (which is why you include the header), but it wont throw errors if it doesn't find the function definitions. When it compiles the cpp files into object code files, it basically leaves "holes" where the function definitions are supposed to go. Then the linker is used to link those object files together into one executable.

    The compiler does, however, need to know the data members of your class because those determine how much memory an object occupies, which is necessary for object creation. Again, these are included in the class definition in the header file included in main.