Doubts about "linkage"

3

I tried to pass to IDE a code I found in a book and some doubts came up.

Code:

newApplication.cpp

#include "stdafx.h"
#include <iostream>
using std::cout;
using std::endl;

#include "GradeBook.h"

int main()
{
    GradeBook gradeBook1("CS101 Introduction to C++ Programming");
    GradeBook gradeBook2("CS102 Data Structures in C++");

    cout << "gradeBook1 created for course: " << gradeBook1.getCourseName()
         << "\ngradeBook2 created for course: " << gradeBook2.getCourseName()
         << endl;
    return 0;
}

GradeBook.h

#pragma once
#include <string>
using std::string;

class GradeBook
{
public:
    GradeBook(string name);
    void setCourseName(string name);
    string getCourseName();
    void displayMessage();

private:
    string courseName;
};

GradeBook.cpp

#include "stdafx.h"
#include <iostream>
using std::cout;
using std::endl;

#include "GradeBook.h"

GradeBook::GradeBook(string name)
{
    setCourseName(name);
}

void GradeBook::setCourseName(string name)
{
    courseName = name;
}

string GradeBook::getCourseName()
{
    return courseName;
}

void GradeBook::displayMessage()
{
    cout << "Welcome to the grade book for\n" << getCourseName() << "!" << endl;
}

1) How does the compiler "know" that the method implementation is in GradeBook.cpp and that in main() there is only the GradeBook.h ?

2) The application only worked after I included #include "stdafx.h" in the file GradeBook.cpp . Why does it happen?

Visual Studio 2017 folder structure

-Dependencias Externas
-Arquivos de Cabeçalho
  *GradeBook.cpp
  *GradeBook.h
  *resource.h
  *stdafx.h
  *targetver.h
-Arquivos de Origem
 *newApplication.cpp
 *stdafx.cpp
-Arquivos de Recurso
 *newApplication.rc
    
asked by anonymous 15.11.2018 / 02:13

1 answer

4
  

1) How does the compiler "know" that the method implementation is in GradeBook.cpp and that in main() there is only the include of GradeBook.h ?

He does not know. Don; t need to know. The implementation just needs to be there. At the time of compiling you say everything you want to be compiled. And at the time of linking it takes everything that is available and brings it together. In that hour he sees if everything he needs has been made available, no matter what order, where he comes from, nothing, unless he is there. If it is not, it gives linkage error.

Once compiled it generates a code and is available to anyone who wants to use it. And even nobody can use it. Although under normal conditions what is not used is not linked together.

  

2) The application only worked after I include #include "stdafx.h" in the file GradeBook.cpp Why does this happen?

Has already been answered: What is "stdafx.h" and what is its importance? .

    
15.11.2018 / 02:31