linker-errors - 对 'print(int)' 的 undefined reference [链接器错误]

标签 linker-errors

作业说:编写一个由两个源文件组成的程序。第一个 (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/

相关文章:

c++ - 在 .intel_syntax GNU C 内联汇编中引用内存操作数

ios5 - 重复的符号_OBJC_CLASS _ $ _ LoginController

c++ - 使用 vector 模板时出现 mingw 链接器错误

linker-errors - 链接错误:未定义对 icu_50::UnicodeString::UnicodeString() 的引用

linux - 从 _start 调用 printf 时出现链接器错误

ios - 链接器错误,但仅限于测试文件

windows - visual studio 2010 express + win sdk = 无法打开输入文件 'kernel32.lib'

c++ - 将 HDF5 库链接到 Visual C++ DLL 项目 : unresolved external symbol __imp__*

c++ - 用于配置 cpp 源文件位置的环境变量

c++ - 链接器错误 : undefined reference to