当我尝试从我创建的 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/