繁体   English   中英

C ++链接器错误

[英]C++ linker error

我是C ++的新手,需要有关名称空间的一些帮助。 以下是我的4个文件:

node.h <--class interface
node.cpp <--implementation
testNodeFunctions.cpp 
testNodeMain.cpp

//node.h
---------------------------------
#include <iostream>
using namespace std;

namespace namespaceName{

    class Node {
    private:
        int data;

    public:
        void setData( int x);
        int getData();

    };
   //and some more functions

}

//node.cpp
-------------------------------------
#include <iostream>
#include "node.h"
using namespace std;

namespace namespaceName {
      //provides implementation of the memeber functions
     int Node::getData() const{
       return data;
     }
     void Node::setData(int x){
     data=x;
     }

}//namespace


//testNodeFunctions.cpp 
-------------------------------------
#include <iostream>
#include "Node.h"
using namespace std;
using namespace namespaceName;

void showData(){
  //creates a Node object and prints some stuff
  Node a=37;
  cout<<a.getValue()<<endl;
}


//testNodeMain.cpp
----------------------------------------------
#include <iostream>
#include "Node.h"

void showData();

int main(){
//calls methods from testNodeFunctions
showData();
}

我不确定当前是否正在定义名称空间。

如何从testNodeMain.cpp文件调用showData()函数。 当前,我收到链接器错误,指出“对namespaceName :: Node :: methodname的未定义引用”

提前非常感谢

好的。 有道理。 我从标头中删除了使用命名空间std。 我正在编译具有main()的testNodeMain.cpp。 TestNodeMain.cpp从testNodeFunctions.cpp调用函数。 testNodeFunctions.cpp创建Node对象。

没有一个完整的编译示例会引起问题,这很难说,但是您似乎忘记了在链接行中包含node.cpp

我不确定当前是否正在定义名称空间。

看起来不错,尽管没有看到您放入的内容,我不能肯定地说。

如何从testNodeMain.cpp文件调用showData()函数?

必须先声明该函数,然后才能调用它。 testNodeMain.cpp#include行之后或在必须从testNodeMain.cpp包含的另一个头文件中添加以下声明:

void showData();

然后您可以从main调用函数:

int main() {
    showData();
}

当前,我收到链接器错误,指出“对namespaceName :: Node :: methodname的未定义引用”

您需要确保正在编译和链接所有源文件,而不仅仅是主文件。 如果您使用的是GCC,则build命令应类似于:

gcc -o testNode testNodeMain.cpp testNodeFunctions.cpp node.cpp

如果在这种情况下仍然出现错误,请检查您是否已经实现了这些方法。 如果您认为有,那么请更新问题中的代码,以包括缺少的方法之一的实现,以便我们为您检查。

在头文件node.h中,您有

    void setData( int x);
    int getData();

在您的node.cpp文件中,您具有:

 int Node::getValue() const{
   return data;
 }
 void Node::setValue(int x){
 data=x;
 }

您需要将Node::getValue() const {}更改为Node::getData() const {} ,或者将头文件中的函数名称更改为int getValue()void setValue (int x)

该类的头文件和实际的.cpp文件中的函数名称应相同。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM