-
More than one file
When compiling more than one file at once, do you have to put the include statements in all the files that need them, or just the main? Example: Can you do this:
Code:
FILE 1:
class A {
public:
int a;
A() {
a = sqrt(3555);
}
};
FILE 2:
class B {
public:
int b;
B() {
b = pow(3344, 4)
}
};
FILE 3:
#include <iostream>
#include <cmath>
using namespace std;
int main() {
A a;
B b;
cout << a.a;
cout << b.b;
}
Or would each file have to include <cmath> ? Thanks :D !
-
Basically if you include libraries in your main.cpp file and underneath that include other .cpp files than you would be OK.
here is an example:
Code:
//MAIN.cpp
#include <iostream>
#include <cmath>
using namespace std;
#include <"file1.cpp">
#include <"file2.cpp">
this works fine as long as file1 doesn't call anything from file 2. If using namespace std; would be placed at the very buttom, than you would have to also tyoe it out in both file1 and file2. Also you don't want to include a file or a library more then once so you could use ifndef.
-
-
Uhh... don't include source files. It can very drastically increase compile time, and is generally not considered good practice. Just include the headers. The headers should have declarations only (except for templated functions/classes), and the source files should implement them. Then, compile your source file into an object file, and link it in.
Include headers in any file where they are needed (i.e. wherever functions are used, or classes instantiated from that header). Protect from multiple inclusions by putting an inclusion guard around the header file.
Code:
// Inclusion guards
#ifndef MY_HEADER_H
#define MY_HEADER_H
// Any includes
// Declarations and template definitions
#endif
If you just have references to a class in a header or pointers (uninstantiated), then you do not need to include the header, you only need forward declarations. Once you instantiate something (on the stack or with 'new'), you need to include the header.