A quick question

Hello everyone.My name is Icy and i am new to this forum.I have started C++ a while ago and this site has been my main source of information.Ok now my question.
Is it possible to import c++ code from another file and use it in another c++ project.For example,let's say i'm making a big project with many functions in it.What if i wrote some of these functions in separate files and then when i needed to call those functions in my main project file i would use a command to do so.I have tried it by including fstream but it outputs the whole source code of the file i imported.I don't know if i explained what i wanted to know.

Thanks in advance.
You need to:
put the source in a separate file
place the declarations of the symbols defined in that file in a header,
#include that header everywhere you use that symbol
compile all the sources and link them together

eg:
1
2
3
4
5
6
7
8
//myfile.cpp

#include "myfile.h"

void foo() // define
{
    do something
}


1
2
3
4
5
6
7
8
//myfile.hpp

#ifndef MY_HEADER  // header guard
#define MY_HEADER

void foo(); // declare

#endif 


1
2
3
4
5
6
7
8
//main.cpp

#include "myfile.h"

int main()
{
    foo(); // call
}


For a more detailed explanation: http://www.cplusplus.com/forum/articles/10627/
why you have to do this?:

#ifndef MY_HEADER
#define MY_HEADER
//...
#endif

what i know is this:

#ifndef MYFILE
#define MYFILE
//...
#endif
1
2
3
4
#ifndef YOU_CAN_PUT_ANY_VALID_IDENTIFIER_IN_HERE_BUT_YOU_MUST_BE_SURE_THAT_IT_IS_NOT_USED_ELSEWHERE
#define YOU_CAN_PUT_ANY_VALID_IDENTIFIER_IN_HERE_BUT_YOU_MUST_BE_SURE_THAT_IT_IS_NOT_USED_ELSEWHERE
//...
#endif 
do you mean, if our header files is myfile.h we can use another identifier, like:
#ifndef ANOTHER_IDENTIFIER_H
#define ANOTHER_IDENTIFIER_H
...
#endif

and,what is header guard? sorry for being "don't know" :D
Last edited on
When the compiler is looking through files, it's not that intelligent. A "header guard" stops the compiler reading the same header information twice, which would make it throw a fit.
When you chose an identifier for your header guard you have to make sure that it's not used elsewhere, so a longer non-trivial identifier is better. Using the filename helps since is unlikely that you have two files with the same name
Topic archived. No new replies allowed.