0

I've borrowed example from this question. There are following files:

main.cpp

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

int main(int argc, char *argv[])
{
int x=42;
std::cout << x <<std::endl;
std::cout << foo(x) << std::endl;
return 0;
}

foop.h

#ifndef FOOP_H
#define FOOP_H
int foo(int a);
#endif

foop.cpp

int foo(int a){
    return ++a;
}

As you can see main.cpp includes foop.h, but foop.h contains only declaration not definition of function foo. How does main.cpp knows about existence of foop.cpp and the definition of foo function? My first guess was that if the name of *.h is the same as of *.cpp then it somehow magically works, but it also worked when I've renamed foop.cpp to foop2.cpp

PS: I keep files under one project, inside same directory inside Visual Studio

PPS: Can I somehow debug the compilation process so I can see what is going on?

Community
  • 1
  • 1
Wakan Tanka
  • 7,542
  • 16
  • 69
  • 122
  • One question per question please, makes it easier to write concise answers or find appropriate dupes if applicable. – Baum mit Augen Aug 26 '16 at 10:54
  • 1
    `I keep files under one project,` - This is the important part. An MSVC++ project simply is a group of files that (once compiled) should be linked together. With files in separate projects, you need to make one project a library project and tell the other project to use that first project. – MSalters Aug 26 '16 at 11:11
  • @MSalters thank you, this should be an answer. – Wakan Tanka Aug 26 '16 at 11:37

1 Answers1

2

The compiler doesn't need to know about the definition. That's the linker's job.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • If I understand correct then when I run build in Visual Studio then compiler compiles all files (if they are syntactically correct, even if they are only function definition without main()) inside project and then linker adds them together by using techniques (symbol tables) mentioned in duplicate question? – Wakan Tanka Aug 26 '16 at 11:10