I am trying to compile two cpp files with a header file.
myHeader.h is:
#ifndef ADD_H
#define ADD_H
void myFunc(double &Num);
#endif
File1.cpp is:
#include <iostream>
#include "myHeader.h"
int main()
{
using std::cout;
using std::endl;
double n=4.0;
myFunc(n);
cout << n << endl;
return 0;
}
File2.cpp is
#include "myHeader.h"
void myFunc(double &Num)
{
using std::cout;
using std::endl;
Num *= 10.0;
cout << "Num = " << Num << endl;
}
I gnu-compile and execute on Windows as:
c++ file1.cpp file2.cpp
./a
I get the following 2 compilation errors:
File2.cpp:6 error: 'std::cout' has not been declared
File2.cpp:7 error: 'std::endl' has not been declared
If I use using namespace std; I still get the errors. It doesn't matter if I compile the two cpp files separately -> same problem. Can someone see what the problem is. Thanks in advance!
Because file2 does not include iostream..
cpp files are compiled separately so what you include in one, doesn't affect the other.
Either include iostream in file2 or in myHeader (then you don't have to include it in file1).
This could also be implemented by saving File2.cpp as a header file. What are the pros and cons of doing that? (In that case, my understanding is that only File1 gets compiled explicitly after the preprocessor prepends the contents of File2.h to File1.cpp. Is this the correct interpretation?)