943,899 Members | Top Members by Rank

Ad:
  • C++ Discussion Thread
  • Unsolved
  • Views: 519
  • C++ RSS
Jul 9th, 2008
0

#include <"iDontGetThis.h">

Expand Post »
Hey,

I have seen some code examples were people include there own files, e.g

C++ Syntax (Toggle Plain Text)
  1. #include <myFile.h>

do i just have to save a file called myFile.cpp?

and if so can i declare a function in myFile and then use it in untitled1 without declaring it just including myFile. Thanks.
Reputation Points: 25
Solved Threads: 4
Junior Poster
Black Magic is offline Offline
177 posts
since Apr 2008
Jul 9th, 2008
1

Re: #include <"iDontGetThis.h">

You would actually name the file myFile.h, not myFile.cpp. When you #include something you are basically taking the contents of the header (*.h) file and dumping them into your current .cpp file. If the file you need to include is in your current working directory (or if you're specifying an absoltue path), use "". If the file is in one of your compiler's include directories, use <>.

It is a bad idea to define functions in a header file. If you have this in myFile.h:
C++ Syntax (Toggle Plain Text)
  1. int MyFunc()
  2. {
  3. return 5;
  4. }

and you have two .cpp files in your project, and they both #include myFile.h, you'll get an error, because you're trying to re-define a function, a no-no. Instead, have prototypes in your header files. Like:
myfile.h
C++ Syntax (Toggle Plain Text)
  1. int MyFunc();

and have definitions in a .cpp file:
myfile.cpp
C++ Syntax (Toggle Plain Text)
  1. #include "myfile.h"
  2.  
  3. int MyFunc()
  4. {
  5. return 5;
  6. }

Then any amount of other files can #include myfile.h with no problem, as long as myfile.cpp is also in the project.

One last thing, it's good to put the code in your header files in #ifndef blocks. Like this:
C++ Syntax (Toggle Plain Text)
  1. #ifndef MY_FILE_H
  2. #define MY_FILE_H
  3.  
  4. int MyFunc();
  5.  
  6. #endif

This way, if you end up #including the same file twice in one .cpp file (which can happen when you have lots of #includes), you won't have an issue, since the code is only executed once.
Last edited by CoolGamer48; Jul 9th, 2008 at 2:37 pm.
Reputation Points: 77
Solved Threads: 40
Posting Pro in Training
CoolGamer48 is offline Offline
401 posts
since Jan 2008

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C++ Forum Timeline: Form1 and Form2
Next Thread in C++ Forum Timeline: String/Class problem(s)!!





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC