作业说:编写一个由两个源文件组成的程序。第一个 (Main.c) 包含 main() 函数并为变量 i 提供一个值。第二个源文件 (Print.c) 将 i 乘以 2 并打印它。 Print.c 包含可以从 main() 调用的函数 print()。
在尝试完成这项作业时,我创建了三个文件: main.cpp
#include <stdio.h>
#include "print.h"
using namespace std;
// Ex 1-5-3
// Global variable
int i = 2;
int main() {
print(i);
return 0;
}
打印.cpp:
#include <stdio.h>
#include "print.h"
using namespace std;
// Ex 1-5-3
// Fetch global variable from main.cpp
extern int i;
void print(int i) {
printf("%d", 2*i);
}
打印.h:
#ifndef GLOBAL_H // head guards
#define GLOBAL_H
void print(int i);
#endif
我编译了 print.cpp,当我尝试编译并运行 main.cpp 时,它显示: [链接器错误]未定义对“print(int)”的引用
为什么它不接受我在 print.cpp 中对 void print (int i) 的定义并通过头 print.h 引用它?谢谢!
最佳答案
不确定您使用的是什么编译器,但我让它在 Linux/gcc 上工作:
$ gcc main.cpp print.cpp -o test
$ ./test
$ 4
$
关于linker-errors - 对 'print(int)' 的 undefined reference [链接器错误],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12851586/