headerfiles

hello ,
i wrote aprogram abc.h
#ifndef abc_h
#define abc_h
#include <iostream.h>
class abc
{
public:
int a,b,c;
void add();
};
#endif

another abc.cpp
#include "abc.h"
abc ::add()
{
cin>>a>>b;
c=a+b;
cout<<c;
}


i add these files in another program
i.e main.cpp
#include "abc.h"
int main()
{
abc a;
a.add();
}



it gives the error as undefined reference of add()
why
how can we solve this
under linux terminal/turboc++
plz help me


This exact same question came up recently, here: http://www.cplusplus.com/forum/beginner/63140/

Here is the same answer:

Undefined reference means that whilst the compiler understands how the function should work (which means it understands the name of the function, the input types and the return type), the linker cannot find the actual compiled code that actually does the work.

In this case, if you #include <abc.h> in your code, the compiler will then find the function prototype, and from that will know the name and parameters. Good so far. Then, everywhere you use the actual function, the compiler effectively leaves a note to the linker, saying "here, you put in the compiled code that actually makes this function call work".

So, then the linker comes along. The compiler has presented it with some compiled code (but NOT the compiled version of abc.cpp, because you have not compiled that, or if you have, you have not told the linker where to find it). The linker then goes looking for the compiled function. It does not find it. It comes back and says "undefined reference". You fix this by compiling abc.cpp and making sure the linker can find it.

Under g++, this would be done simply:

g++ main.cpp abc.cpp to build.

Under Turbo C++, who knows how it's done. The above, though, is a simple explanation of your problem.
From your abc.h
1
2
3
4
5
6
class abc
{
  public:
    int a,b,c;
    void add(); // add return value explicitly set to void
};


From your abc.cpp
1
2
3
4
5
6
abc ::add() // add return value not set
{
  cin>>a>>b;
  c=a+b;
  cout<<c;
}


Change the value in the cpp from abc::add() to `void abc::add()'

EDIT: I somehow had it in my addled brain that there was an implicit int return type in C++, which I found from research was wrong.
Last edited on
closed account (1yR4jE8b)
You could also compile everything separtely, and then manually link:

1
2
3
g++ -c main.cpp -o main.o
g++ -c abc.cpp -o abc.o
g++ main.o abc.o
suppose we r using any IDE like VC++ ,DEV c++ inthat we are not using like that we are not include abc.cpp file to main.cpp but ,here its working fine, why shouldnt in terminal mode
Topic archived. No new replies allowed.