CPrimer中建议在头文件中声明函数,在源文件中定义函数。这样能够确保同一函数的所有声明一致,而且一旦我们想要改变函数接口只要改变一条声明即可。
但是在实现过程中出现了一下问题。现记录,为进一步探究编译器工作方式作为知识储备。
//Myprint.h
#ifndef MYPRINT_H_INCLUDED
#define MYPRINT_H_INCLUDED
#include <iostream>
using namespace std;
void Myprint();
#endif // MYPRINT_H_INCLUDED
//Myprint.cpp
#include "Myprint.h"
#include <iostream>
using namespace std;
void Myprint()
{
cout << "my own function!";
}
//main.cpp
#include <iostream>
#include "Myprint.h"
using namespace std;
int main()
{
Myprint();
return 0;
}
调用自定义函数,在编译时发生一下错误 undefined reference to "Myprint.cpp"...ld returned 1 exit status
通过查阅资料找出原因,参考:https://blog.csdn.net/dyzhen/article/details/79815667
通过分析,我认为是编译器找不到Myprint.cpp的函数实现主体导致的编译错误。决定手动尝试g++/gcc编译
参考https://www.cnblogs.com/mjk961/p/7862170.html(g++编译多文件)
https://www.cnblogs.com/testlife007/p/6555404.html(gcc命令与参数)
由于我没有保存Myprint.cpp文件,所以编译时出现了No such file or directory 的错误!
在修正后,采用 g++ -c main.cpp 生成 main.o文件;
g++ -c Myprint.cpp 生成 Myprint.o文件;
g++ main.o Myprint.o -o test 生成可执行文件 test.exe;
执行test .exe输出如图。
也可以采用 g++ -o Own_Fuction(上级路径) main.cpp Myprint.cpp 一歩到位直接生成可执行文件。
-
解决方法:手动编译分开编译或在编译前加上路径
-
ps:在codeblocks中编译多个文件,应该右击project文件,点击add_file;