Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to link header files in c++

I'm new to programming in C++ 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 isn't it working, and how can I fix it?

like image 234
siri Avatar asked Sep 27 '10 14:09

siri


People also ask

How are header files linked in C?

A common convention in C programs is to write a header file (with . h suffix) for each source file (. c suffix) that you link to your main source code.

What is linking in C compiler?

Linking is the process of collecting and combining various pieces of code and data into a single file that can be loaded (copied) into memory and executed.

What are the two ways of representing header files in C program?

There are of 2 types of header file: Pre-existing header files: Files which are already available in C/C++ compiler we just need to import them. User-defined header files: These files are defined by the user and can be imported using “#include”.


3 Answers

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.

like image 149
sbi Avatar answered Oct 16 '22 15:10

sbi


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

g++ ex2.cpp a.cpp -o my_program
like image 9
Oliver Charlesworth Avatar answered Oct 16 '22 14:10

Oliver Charlesworth


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

g++ -Wall -pedantic -g -o your_exe a.cpp ex2.cpp
like image 5
Nikolai Fetissov Avatar answered Oct 16 '22 14:10

Nikolai Fetissov