我是使用头文件进行 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
文件并使用生成的目标文件调用链接器。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)