【发布时间】:2016-01-15 19:44:14
【问题描述】:
pid.h
#include <iostream>
template <class T>
void f(T t);
pid.c
#include "pid.h"
template <class T>
void f(T t) {
std::cout << t;
}
template
void f<int>(int);
pid2.c
#include "pid.h"
template <class T>
void f(T t) {
std::cout << 55;
}
template
void f<int>(int);
main.c
#include "pid.h"
int main()
{
f(1);
return 0;
}
命令:
g++ "-IC:\\Users\\kam\\workspace\\boost_1_56_0" -O0 -g3 -pg -Wall -c -fmessage-length=0 -std=c++11 -pthread -o "src\\pid2.o" "..\\src\\pid2.cpp"
g++ "-IC:\\Users\\kam\\workspace\\boost_1_56_0" -O0 -g3 -pg -Wall -c -fmessage-length=0 -std=c++11 -pthread -o "src\\pid.o" "..\\src\\pid.cpp"
g++ "-IC:\\Users\\kam\\workspace\\boost_1_56_0" -O0 -g3 -pg -Wall -c -fmessage-length=0 -std=c++11 -pthread -o "src\\main.o" "..\\src\\main.cpp"
g++ -pg -o Hello_World.exe "src\\pid2.o" "src\\pid.o" "src\\main.o"
结果:
55
现在,如果我将 pid.c 和 pid2.c 中的函数设为非模板化,我会得到多重定义错误。
【问题讨论】:
-
猜测,可能是编译器在使用“多个函数定义”这个短语时所暗示的多个函数定义。不过,只是猜测。
-
顺便说一句,在标头中包含
<iostream>是一种不好的做法,因为这会强制客户端代码支持标头的整个复杂性。相反,在实际可行的情况下,请使用<iosfwd>。 -
@Cheersandhth.-Alf 我只是通过一个例子来说明一点;但无论如何感谢您的评论。
-
这可能取决于用于编译和链接代码的特定命令。你能提供这些信息吗?
-
如果你在命令行切换
pid.o和pid2.o的顺序,我希望你得到不同的输出。是这样吗?