如何链接头文件在c ++ [英] how to link header files in c++

查看:124
本文介绍了如何链接头文件在c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始用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;  
}



当我尝试使用 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

如何解决?

推荐答案

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

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.

从错误消息看来,您使用的是GCC。如果是这样,我想你可以做

g ++ ex2.cpp a.cpp

让它编译 .cpp 文件,并使用生成的目标文件调用链接器。

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.

这篇关于如何链接头文件在c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆