Show Lecture.ImplicitInclusion as a slide show.
Is this code correct?
#include <iostream> using namespace std; int main() { string s = "Han shot first!\n"; cout << s; }
Han shot first!
#include <iostream> using namespace std; int main() { string s = "Han shot first!\n"; cout << s; }
Han shot first!
The code is not correct. A std::string
was defined,
but there is no #include <string>
. But, still, it compiled. ☺? ☹?
operator<<
cout << s;
. This meaning of <<
isn’t
built into C++ like integer addition. Instead, somebody must have
written a operator<<
function that takes an ostream
and a
std::string
.
<iostream>
or <string>
.
ostream
and string
.
<iostream>
, then <iostream>
has to #include <string>
.
<string>
, then <string>
has to #include <iostream>
.
#include <iostream> using namespace std; int main() { string s = "Han shot first!\n"; cout << s; }
Han shot first!
<iostream>
includes <string>
.
<string>
might include <iostream>
.
Remember include guards? They work like this:
<Foo.h> contains: #ifndef FOO_H_INCLUDED #define FOO_H_INCLUDED … define the class Foo here … #endif /* FOO_H_INCLUDED */
We don’t usually bother with the indentation.
One could construct <iostream>
& <string>
so they don’t
#include
each other:
IOSTREAM_INCLUDED
,
used for #include
guards?
#include
d.
#include
d.
<iostream>
and <string>
get included,
then define operator<<
.
<<
, because they won’t need it.
<iostream>: #ifndef IOSTREAM_INCLUDED #define IOSTREAM_INCLUDED #ifdef STRING_INCLUDED #include <string-output-operator> #endif #endif /* IOSTREAM_INCLUDED */ <string>: #ifndef STRING_INCLUDED #define STRING_INCLUDED #ifdef IOSTREAM_INCLUDED #include <string-output-operator> #endif #endif /* STRING_INCLUDED */ <string-output-operator>: std::ostream &operator<<(std::ostream &, const std::string &);
#include <iostream> #include <string> using namespace std; int main() { string s = "Han shot first!\n"; cout << s; }
Han shot first!
#include
what you need.
Consider this program, compiled on my Macbook Air under macOS:
% cat c.cc #include <cmath> int main() { return isinf(0.0); } % g++ c.cc % ./a.out % g++ --version Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1 Apple LLVM version 8.0.0 (clang-800.0.42.1) Target: x86_64-apple-darwin15.6.0 Thread model: posix InstalledDir: /Library/Developer/CommandLineTools/usr/bin
The same program, compiled on a CSU CS Department computer:
% cat c.cc #include <cmath> int main() { return isinf(0.0); } % g++ c.cc c.cc: In function ‘int main()’: c.cc:3:12: error: ‘isinf’ was not declared in this scope return isinf(0.0); ^~~~~ c.cc:3:12: note: suggested alternative: In file included from c.cc:1:0: /usr/include/c++/7/cmath:612:5: note: ‘std::isinf’ isinf(_Tp __x) ^~~~~ % g++ --version g++ (GCC) 7.3.1 20180130 (Red Hat 7.3.1-2)
TEST ON THE TARGET MACHINE