【发布时间】:2017-02-23 07:04:08
【问题描述】:
himake: hello.o printing.o name.o
g++ -o himake hello.o printing.o name.o
hello.o: hello.cpp
g++ -c hello.cpp
printing.o: printing.cpp
g++ -c printing.cpp
name.o: name.cpp
g++ -c name.cpp
运行上面的 makefile 会出现以下错误:
[alex@pcc 目录]$ make g++ -o himake hello.o print.o name.o
hello.o:在函数“main”中:
hello.cpp:(.text+0xc8): undefined reference to `printHello(std::basic_string, std::allocator >)'
collect2: ld 返回 1 个退出状态
make: *** [himake] 错误 1
文件: 你好.cpp:
// hello.cpp
// standard library
#include <iostream>
#include <string>
using namespace std;
// user defined header files
#include "name.h"
#include "printing.h"
int main ()
{
string name;
name = getName(); // getName is in name.h
printHello(name); // printHello is in print.h
return 0;
}
名称.cpp
// name.cpp
// user defined header files
#include "name.h"
#include "printing.h"
string getName()
{
string name;
printGreeting(); // printGreeting is from print.h
getline(cin, name);
return name;
}
名称.h
// name.h
#include <iostream>
using namespace std;
string getName();
打印.cpp
// printing.cpp
// user defined include files
#include "printing.h"
void printGreeting(void)
{
cout << "Your name: ";
return;
}
void printHi (string name)
{
cout << "Hi, " << name << endl;
return;
}
打印.h
// printing.h
#include <iostream>
using namespace std;
void printGreeting();
void printHello(string);
【问题讨论】:
-
如果该代码准确,则函数 printHello 未定义。函数名需要完全匹配
-
printHi或printHello? -
天哪,原来如此
-
在不相关的注释上,请阅读“using namespace” in c++ headers。不要在头文件中使用
using namespace std;。有很多例子可以说明为什么稍微搜索一下就不好。我也推荐阅读Why is “using namespace std” considered bad practice?。
标签: c++ linux makefile gnu-make