tags:

views:

589

answers:

3

I am working in Visual C++. I have two .cpp files in the same source file. How can I access another class (.cpp) function in this main .cpp?

+1  A: 

You should put the function declarations in an .hpp flie, and then #include it in the main.cpp file.

For instance, if the function you're calling is:

int foo(int bar)
{
   return bar/2;
}

you need to create a foobar.hpp file with this:

int foo(int bar);

and add the following to all .cpp files that call foo:

#include "foobar.hpp"
Nathan Fellman
simply said,another.cppclass A{-----}and in main.cpp ,here is there's is any possibilities to create an object to class A in main.cpp?
Rajakumar
thanks Nathan Fellman
Rajakumar
+4  A: 

You should define your class in a .h file, and implement it in a .cpp file. Then, include your .h file wherever you want to use your class.

For example

file use_me.h

#include <iostream>
class Use_me{

   public: void echo(char c);

};

file use_me.cpp

#include "use_me.h" //use_me.h must be placed in the same directory as use_me.cpp

void Use_me::echo(char c){std::cout<<c<<std::endl;}

main.cpp

#include "use_me.h"//use_me.h must be in the same directory as main.cpp
    int main(){
       char c = 1;

       Use_me use;
       use.echo(c);

       return 0;

    }
Tom
Tom,Can i access use_me function without creating header file...
Rajakumar
Sure you can. Copy the `Use_me` class declaration and paste it in place of the `#include` directives in *main.cpp* and *use_me.cpp*. That's essentially what `#include` does anyway. You would be stupid for doing that, but it's certainly possible to do.
Rob Kennedy
+1  A: 

Without creating header files. Use extern modifier.

a.cpp

extern int sum (int a, int b);

int main()
{
    int z = sum (2, 3);
    return 0;
}

b.cpp

int sum(int a, int b)
{
    return a + b;
}
Vova
thanks ...Vova
Rajakumar
I'm pretty sure functions have extern linkage by default anyway. You only need `extern` on variables.
Rob Kennedy