How to link header files in C ++

I am new to C ++ programming with header files. This is my current code:

//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 it with g++ ex2.cpp, I get this 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

Why is it not working, and how can I fix it?

+5
source share
4 answers

You do not link header files. You link object files that are created by compiling files .cpp. You need to compile all the source files and transfer the resulting object files to the linker.

, GCC. , , g++ ex2.cpp a.cpp
.cpp .

+23

, :

g++ ex2.cpp a.cpp -o my_program
+8

, (.cpp):

g++ -Wall -pedantic -g -o your_exe a.cpp ex2.cpp
+3

ex2.cpp, def , a.cpp, a.cpp, :

g++ ex2.cpp a.cpp

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

+2
source

All Articles