tags:

views:

120

answers:

4

Hi iam new to write programs in c++ by using header files and including them.

//a.h
#ifndef a_H
#define a_H
namespace hello
{
  class A
  {
    int a;
    public:
      void setA(int x);
      int getA();
  };
} 
#endif

//a.cpp
#include "a.h"
namespace hello
{
   A::setA(int x)
  {
    a=x;
  }
  int A::getA()
  {
    return a;
  }
}

//ex2.cpp
#include "a.h"
#include<iostream>
using namespace std;

namespace hello
{
  A* a1;
}
using namespace hello;
int main()
{
  a1=new A();
  a1->setA(10);
  cout<<a1->getA();
  return 1;  
}

when i try to compile using g++ ex2.cpp iam getting the following error

In function `main':
ex2.cpp:(.text+0x33): undefined reference to `hello::A::setA(int)'
ex2.cpp:(.text+0x40): undefined reference to `hello::A::getA()'
collect2: ld returned 1 exit status

is there any other way to compile this please any one help me

+1  A: 

Currently you are compiling and linking only ex2.cpp but this file has makes use of class def and function calls present in a.cpp so you need to compile and link a.cpp as well as:

g++ ex2.cpp a.cpp

The above command will compile the source file(.cpp) into object files and link them to give you the a.out executable.

codaddict
+7  A: 

You don't link header files. You link object files, which are created by compiling .cpp files. You need to compile all your source files and pass the resulting object files to the linker.

From the error message it seems you're using GCC. If so, I think you can do
g++ ex2.cpp a.cpp
to have it compile both .cpp files and invoke the linker with the resulting object files.

sbi
+1 for `You don't link header files`. :)
Prasoon Saurav
+4  A: 

You need to compile and link both source files, e.g.:

g++ ex2.cpp a.cpp -o my_program
Oli Charlesworth
+1  A: 

You need to compile and then link both source (.cpp) files:

g++ -Wall -pedantic -g -o your_exe a.cpp ex2.cpp
Nikolai N Fetissov
May I suggest `-Werror` as well :) ?
Matthieu M.