代码之家  ›  专栏  ›  技术社区  ›  onavarro

一个非常简单的c++程序中的“未定义引用”错误

  •  1
  • onavarro  · 技术社区  · 12 年前

    我有一个简单的程序,我完全复制了 http://www.learncpp.com/cpp-tutorial/19-header-files/ 因为我正在学习如何用多个文件制作c++程序。

    程序会编译,但在生成时,会出现以下错误:

    /tmp/ccm92rdR.o:在函数主体中: main.cpp:(.text+0x1a):对“add(int,int)”的未定义引用 collect2:ld返回1退出状态

    这是代码:

    主.cpp

    #include <iostream>
    #include "add.h" // this brings in the declaration for add()
    
    int main()
    {
        using namespace std;
        cout << "The sum of 3 and 4 is " << add(3, 4) << endl;
        return 0;
    }
    

    添加.h

    #ifndef ADD_H
    #define ADD_H
    
    int add(int x, int y); // function prototype for add.h
    
    #endif
    

    添加.cpp

    int add(int x, int y)
    {
        return x + y;
    }
    

    有人知道为什么会发生这种事吗?

    非常感谢你。

    2 回复  |  直到 12 年前
        1
  •  5
  •   wallyk    3 年前

    代码几乎是完美的。

    添加一行 #include "add.h" 在里面 add.cpp .

    将文件编译为 g++ main.cpp add.cpp 它将生成一个可执行文件 a.out

    您可以将可执行文件运行为 ./a.out 它将产生输出“3和4的和是7”(没有引号)

        2
  •  0
  •   L30nardo SV.    12 年前

    当有许多.c或.cpp源并且其中一些源未编译时,可能会发生未定义的引用。

    关于如何做到这一点,一个很好的“循序渐进”的解释是 here