如何在c ++中链接头文件

sir*_*iri 5 c++ gcc compilation

我是用C++编写头文件的新手.这是我目前的代码:

//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;  
}
Run Code Online (Sandbox Code Playgroud)

当我尝试编译它时g++ ex2.cpp,我收到此错误:

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
Run Code Online (Sandbox Code Playgroud)

为什么不工作,我该如何解决?

sbi*_*sbi 28

您没有链接头文件.链接目标文件,这些文件是通过编译.cpp文件创建的.您需要编译所有源文件并将生成的对象文件传递给链接器.

从错误消息看,您似乎正在使用GCC.如果是这样,我认为你可以
g++ ex2.cpp a.cpp
让它编译两个.cpp文件并使用生成的目标文件调用链接器.


Oli*_*rth 8

您需要编译和链接两个源文件,例如:

g++ ex2.cpp a.cpp -o my_program
Run Code Online (Sandbox Code Playgroud)


cod*_*ict 5

目前您仅进行编译和链接ex2.cpp,但该文件使用了类 def 和函数调用,a.cpp因此您需要编译和链接a.cpp以及:

g++ ex2.cpp a.cpp
Run Code Online (Sandbox Code Playgroud)

上面的命令会将源文件(.cpp)编译成目标文件并链接它们以提供a.out可执行文件。


Nik*_*sov 5

您需要编译然后链接两个源 ( .cpp) 文件:

g++ -Wall -pedantic -g -o your_exe a.cpp ex2.cpp
Run Code Online (Sandbox Code Playgroud)