3
I tried to pass to IDE a code I found in a book and some doubts arose.
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 the compiler manages to "know" that the implementation of the method is in GradeBook.cpp
whereas in the main()
only exists the include of GradeBook.h
?
2) The application only worked after I included #include "stdafx.h"
in the archive
GradeBook.cpp
. Why does this 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
After the "compiler" finds the implementation of the Gradebook.cpp methods, it "pulls" everything together into one file before generating the object code ?
– Igor PTZ
@Rogi93 , some time ago I distanced myself from the C world, and even more from the C++ world, so I may be talking nonsense... the object file is composed of open symbols, variables and implemented functions (these last two solved symbols). The linker takes the open symbols and checks to see if there are any objects that solve it. So it is normal and expected that the object file has no solved symbols referring to things outside its internal context. This "pull everything" occurs in linkediting, where the executable is generated. There must be something in the gold mine that are the answers of Maniero, just look
– Jefferson Quesado
@Rogi93, I found two of my answers on the subject. The first: https://answall.com/a/213804/64969, and the second: https://answall.com/a/306915/64969 (which mentions the first)
– Jefferson Quesado
Thank you Jefferson, you’ve helped a lot
– Igor PTZ