I'm trying to write a function in a file, and be able to use it in multiple other files in that project. Is there a way to do this?
Thanks
I'm trying to write a function in a file, and be able to use it in multiple other files in that project. Is there a way to do this?
Thanks
Yes, you create a .cpp file with the function you write, then in other files you #include "thefile.cpp" into the other cpp files you want to use the function in
ex
mystring.cpp has string functions you wrote.
then in main.cpp
#include "mystring.cpp" would give you access to those functions
Hmm thanks, but I have the following and it doesn't work:
test.cpp:
----------------------------
#include " test2.cpp"
int main(void)
{
hi();
return 0;
}
----------------------------
test2.cpp:
----------------------------
#include<iostream.h>
void hi(void)
{
cout << "hi" << endl;
}
----------------------------
I get this error:
Compiling...
test2.cpp
Linking...
test2.obj : error LNK2005: "void __cdecl hi(void)" (?hi@@YAXXZ) already defined in test.obj
Debug/test.exe : fatal error LNK1169: one or more multiply defined symbols found
Error executing link.exe.
Thanks!
Ok, welcome to the world of header files. Create a header file named test2.h and in it put the function protoypes that you would like to use:
Then create test2.cpp and place the function definitions prototyped in the header file.Code://-----------test2.h--------------------------- void hi();
Then in your main file include your header file and let the linker do the rest:Code:/*---------------test2.cpp------------------------*/ #include "test2.h" #pragma once #include <iostream> using namespace std; void hi(){ cout<<"hi"<<endl; }
Code:/*---------------test.cpp---------------------------*/ #include "test2.h" #pragma once #include <iostream> using namespace std; int main(){ hi(); cin.get(); return(0); }
Great, thanks!
One more question: I notice you still include iostream in main even though you're also including test2 which has iostream included. For example:
hi.cpp:
main.cppCode:#include "hi.h" #include<iostream.h> void hi() { cout << "hi" << endl; }
Thanks!Code:#include "hi.h" #include<iostream.h> //do I still need this? int main() { hi(); cin.get(); return 0; }
You don't nned it as long as your main.cpp file doesn't access anything found in that file, aka cin, cout. However if they do then yes you do still need to declare it. However this isn't as gross of memory use as one may seem to believe due to the '#pragma once' preprocessor directive which will have the compiler add the include file only once.
Ok, thanks.