我设法解决了这个问题,但我不明白为什么会这样,所以我只是在寻找对此的澄清,欢迎任何解释。
我正在做 Bruce Eckel 书中的练习:Thinking in C++。 第 1 卷第 4 章中的练习 13 正在创建“代表视频出租商店中的录像带的抽象数据类型” 根据本章的主题,我假设这应该是一个结构,就像这个非常简单的结构:
//video.h
typedef struct {
unsigned id;
char* title;
float length;
int inRent;
void printout();
} Video;
使用虚拟实现,例如:
//video.cpp
#include "stdio.h"
#include "video.h"
void Video::printout(){
printf("id:%u, title:%s, length:%f\n",this->id,this->title,this->length);
}
和像这样的 main.cpp:
//main.cpp
#include "video.h"
#include "stdio.h"
int main(){
Video first;
first.id=1;
first.title="Some title";
first.length=1.5;
first.printout();
return 0;
}
当尝试使用 gcc -o main.exe main.cpp video.cpp -lstdc++
进行编译和链接时,我在链接时收到以下错误。我也用 g++ 得到了相同的结果
C:\Users\jani\AppData\Local\Temp\cc1KIhpp.o:main.cpp:(.text+0x2e): undefined reference to `Video::printout()'
当我使用结构标识符时 - 如:typedef struct some_id {...} Video;
- 编译和运行没有错误。
这个结构声明在类似情况下如何工作? Eckel 说:“你会注意到结构标识符在一开始就被忽略了,因为目标是创建 typedef。但是,有时你可能需要在定义过程中引用结构。(.. .)”。 这适用于哪些情况?
非常感谢您的回答。
亚诺斯
最佳答案
为什么不在 video.cpp 文件中提供 stdio 或 iostream header 。这些 header 根据您的系统提供动态链接。如果您只是从一个简单的 Makefile 进行手动链接,它可能与操作系统和硬件无关。
更重要的是,您没有在主文件中使用任何 C/C++ 库函数,因此无需在主文件中包含 stdio.h。而是将其包含在 video.c 文件中
关于C++ 结构声明 collect2 : ld returned 1 exit status,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30869277/