c++ - 对 randomInteger 的 undefined reference

标签 c++

当我尝试从我创建的 header 中包含一个使用函数时遇到问题。 下面是我的头文件:random.h

#ifndef _random_h
#define _random_h

int randomInteger(int low, int high);

#endif // _random_h

接下来是我的实现文件:random.cpp

#include <iostream>
#include "random.h"
using namespace std;

int randomInteger(int low, int high)
{
    return 1200;
}

下面是我的主程序:helloworld.cpp

#include <iostream>
#include "random.h"


int main()
{
    int num = randomInteger(10, 110);
    std::cout << num << std::endl;
    return 0;

}

当我运行我的主程序时出现错误,它说 对 randomInteger(int, int) 的 undefined reference 。

最佳答案

您需要使用 -c 标志(假设 gcc/g++)编译 random.cpp 和 helloworld.cpp,仅用于编译。因为这只会为您创建一个目标文件,而不会寻找特定的主要功能()

然后你需要用这样的东西编译 g++ -o myprogramtorun random.o helloworld.o

或者您可以像这样一步完成:

g++ -o myprogramtorun random.cpp helloworld.cpp 但这变得不可持续了

关于c++ - 对 randomInteger 的 undefined reference ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20688159/

相关文章:

c++ - boost::shared_ptr 循环依赖

c++11 在信号处理程序中使用条件变量

c++ - 追踪元素和怪物位置

c++ - SIMD 内在函数 - 它们可以在 GPU 上使用吗?

c++ - 启动浏览器的 Posixy 方式?

c++ - 可变多维数组

c++ - DirectX C++ 的链接器错误

c++ - CUDA:内存限定符的非法组合

c++ - 从 C++ 类自动将属性成员生成为字符串?

c++ - 使用 vector 和类