Calling function from different C++ file within the same project

Hi,
I am currently working in a project. I have a function bitcount(int); in one one project file lets say "a.cpp" and i have a header "a.h" where i have defined that function. That function simply finds out the number of bits in a number. Now, I have another file "b.h" and "b.cpp". In "b.cpp" i need to call that function again. I tried few steps like including "a.h" in either "b.h" or "b.cpp" but I got errors. May be i am doing it a wrong way? Any suggestions? Here is what i did.
"a.h"
#ifndef A_H
#define A_H

class AX : public FU{
..
..
public:
int bitcount(int);
...
..
};
#endif

"a.cpp"
#include "a.h"
..
..
int X = bitcount(9);
cout << X;

int AX::bitcount(int x){
...
...
return bit_count;
}

"b.h"
# All includes

class BX: public FU{
private:
..
..
public:
..
..
};
#endif

"b.cpp'
#include "b.h"
...
..

Y = bitcount(200); // How to perform this operation?
cout << Y;

- Regards
You need to make sure that your linker is linking against the (compiled) cpp files that contain the code.

If you're using an IDE, I expect you need to put the cpp files in your "project" or whatever it calls them.
Sorry, I did not understand what you mean. Actually, what i am doing is the simulation project. Simulation is defined inside "main.cpp" where I have included all the headers. I am using an Eclipse for the project.
Put all the cpp files in your project. This is NOT the same as using #include .
Just wondering- can the extern keyword be used in such a scenario?
No, not with functions.
@Moschops: I have all the files in a project.
Well then there's no problem calling functions in one cpp file that are defined in another.
But can you please give me some suggestions on how to proceed?
Here is a sample program. See what it does that yours does not.

a.h
1
2
3
4
5
6
7
8
#include <iostream>
class a
{
  public:
  int x;
  void display();
 
};



a.cpp
1
2
3
4
#include "a.h"
using namespace std;

void a::display() { cout << "I am in a.cpp";}


main.cpp
1
2
3
4
5
6
#include "a.h"
int main()
{
  a anObject;
  anObject.display();
}

This sample program works fine but mine does not work somehow. In my case, i have another files "b.h' and "b.cpp" and i tried to call display(); from "b.cpp". So I just tried to create an object in "b.cpp" for "a" but i got error message. My "b.cpp" looks loke this:

#include "a.h"

void X::FU()
{
int x, y;
a anObject;
anObject.display(200);
}
Last edited on
We are not psychic. We cannot guess error messages. Tell us the error message.
Topic archived. No new replies allowed.