2

Consider the code below:

//header.h
#pragma once

class A
{
public:
    A();
    void f();
};

//header.cpp   
#include "header.h"

A::A(){}
void A::f(){}

//main.cpp
#include "header.h"  

int main()
{
    A a;
    a.f();
}

So how the compiler knows where exactly is the declaration of the constructor and f function, because only the header.h in included in main.cpp? And why cant it find the same functions when the class A is template??

Eduard Rostomyan
  • 7,050
  • 2
  • 37
  • 76
  • Functions, including constructors, can be referred to symbolically. The linker looks up all the symbols and replaces them with the actual code addresses. – Kerrek SB Jul 13 '15 at 09:08
  • possible duplicate of [How does the compilation/linking process work?](http://stackoverflow.com/questions/6264249/how-does-the-compilation-linking-process-work) – Piotr Siupa Jul 13 '15 at 09:09
  • For your last question, see [Why can templates only be implemented in the header file](http://stackoverflow.com/q/495021/597607) – Bo Persson Jul 13 '15 at 09:30

2 Answers2

6

Let me show you this image: c++ flow
(source: mcmahon at faculty.cs.niu.edu)

The compilation process looks like this:

  1. The C++ preprocessor copies the contents of the included header files into the source code file, generates macro code, and replaces symbolic constants defined using #define with their values.

  2. The expanded source code file produced by the C++ preprocessor is compiled into the assembly language for the platform.

  3. The assembler code generated by the compiler is assembled into the object code for the platform.

  4. The object code file generated by the assembler is linked together with the object code files for any library functions used to produce an executable file.

Community
  • 1
  • 1
Ashot
  • 81
  • 4
4

A compilation unit does not require the definition, just a declaration.

The linker will make sure that all function definitions can be found from all the constituent compiled units.

A template class is only instantiated at the point of use, and that is on a function-by-function basis. It's for that reason that template classes tend to be fully defined in headers.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483