gpt4 book ai didi

c++ - C++中如何链接头文件

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:48:33 25 4
gpt4 key购买 nike

我不熟悉使用头文件使用 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;
}

当我尝试用 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 文件创建的。您需要编译所有源文件并将生成的目标文件传递给链接器。

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

关于c++ - C++中如何链接头文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3804703/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com