Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between using and include in c++?

Tags:

c++

I know that include is for classes and using is for some built-in stuff, like namespace std... When you include something, you can create objects and play around with them, but when you are "using" something, then you can use some sort of built-in functions. But then how am I supposed to create my own "library" which I could "use"?

like image 985
user2030383 Avatar asked Mar 20 '13 15:03

user2030383


2 Answers

Simply put #include tells the pre-compiler to simply copy and paste contents of the header file being included to the current translation unit. It is evaluated by the pre-compiler.

While using directive directs the compiler to bring the symbol names from another scope in to current scope. This is essentially put in effect by the compiler.

But then how am I supposed to create my own "library" which I could "use"?

Namespaces are something which are used for preventing symbol name clashes. And usually every library implementer will have their functionality wrapped up in one or many namespaces.

like image 113
Alok Save Avatar answered Sep 28 '22 08:09

Alok Save


'include' basically does a copy-paste the value of a file to the location of the "include" line. This is used to make your source code (usually .c file) aware of a declaration of other source code (usually sits in .h file).

'using' basically tells the compiler that in the next code you are using something (usually a namespace) so you won't have to do it explicitly each time:

Instead of:

std::string a;
std::string b;
std::string c;

You could write:

using namespace std;
string a;
string b;
string c;
like image 20
Roee Gavirel Avatar answered Sep 28 '22 07:09

Roee Gavirel