未定义对功能代码块的引用 [英] undefined reference to function code blocks

查看:187
本文介绍了未定义对功能代码块的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

main.cpp

  #include< iostream> 
#include< string>
using namespace std;

void echo(string);

int main()
{
echo(hello);
cout<< 你好,世界! << endl;
return 0;
}

print.cpp

  #include< iostream> 
#include< string>
void echo(string code){
cout<<码;
}

在代码块12.11中编译代码后, / p>

 未定义引用`echo(std :: string)

我使用windows 7 x64。
我已经添加了目录;项目>构建选项>搜索目录并添加当前工作目录。
所有文件都在一个控制台项目中的代码块

解决方案

我相信你应该多读一些命名空间使用。您在print.cpp中缺少std。



通常,在开始学习cpp或掌握语言时,应该始终尝试写入类的全名命名空间。最终与实践和一些疏忽(如现在),你会了解为什么你真的需要他们。简而言之,命名空间很棒:




  • 当您在多个文件上编写代码时



  • 此外,还应使用 using namespace std;



    无论如何,尝试将代码更改为:

      #include< iostream> 
    #include< string>
    void echo(std :: string code){
    std :: cout< ; code;
    }

    然后你的结果将如下所示:

     > g ++ main.cpp print.cpp -o a.out 

    > ./a.out
    helloHello world!


    main.cpp

    #include <iostream>
    #include <string>
    using namespace std;
    
    void echo(string);
    
    int main()
    {
        echo("hello");
        cout << "Hello world!" << endl;
        return 0;
    }
    

    print.cpp

    #include <iostream>
    #include <string>
    void echo(string code){
       cout << code;
    }
    

    After compiling the code in code blocks 12.11, it gives me that error:

    undefined reference to `echo(std::string)
    

    I use windows 7 x64. I have added the directory; Project>build options > search directories and added the current working directory. All the files are in one console project in code blocks

    解决方案

    I believe you should read up a bit more on namespaces usage. You are missing std in print.cpp.

    Generally, while starting to learn cpp or getting a grip of the language you should always try writing full names of the classes along with the namespaces. Eventually with practice and some oversights (like now) you will learn why you really need them. In a nutshell namespaces are great:

    • When you are writing code over multiple files
    • Compartmentalize your code into separate blocks.

    Also, using namespace std; should be used within cpp files mostly (otherwise headers get mangled up.

    Anyways, try changing your code to this:

    #include <iostream>
    #include <string>
    void echo(std::string code){
        std::cout << code;
    }
    

    Then your results will look like this:

     > g++ main.cpp print.cpp -o a.out
    
     > ./a.out
    helloHello world!
    

    这篇关于未定义对功能代码块的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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