c++中如何链接头文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3804703/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 13:47:40  来源:igfitidea点击:

how to link header files in c++

c++gcccompilation

提问by siri

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

我是 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;  
}

When I try to compile it with g++ ex2.cpp, I get this error:

当我尝试使用 编译它时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

Why isn't it working, and how can I fix it?

为什么它不起作用,我该如何解决?

回答by sbi

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

您不链接头文件。您链接目标文件,这些文件是通过编译.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 .cppfiles and invoke the linker with the resulting object files.

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

回答by Oliver Charlesworth

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

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

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

回答by Nikolai Fetissov

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

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

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

回答by codaddict

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

目前您仅在编译和链接,ex2.cpp但此文件使用了类定义和函数调用,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 the a.outexecutable.

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