包含编译模板

test.h

#ifndef TEST_H_
#define TEST_H_

template<typename T>
void test(T t);

#include "test.cpp"

#endif

test.cpp

#include "test.h"
#include <iostream>

template<typename T>
void test(T t)
{
    std::cout << "it's a template test.." << std::endl;
}

main.cpp

#include "test.h"

int main()
{
    test(1);
    return 0;
}

Makefile

srcs=$(wildcard *.cpp)
objs=$(patsubst %.cpp, %.o, $(srcs))
$(info $(srcs))
$(info $(objs))

all:main
    main:$(objs)
g++ -o $@ $^
    %.o:%.cpp
g++ -c $&amp;amp;amp;lt;

.PHONY:clean
clean:
    rm -f *.o

编译结果:
test.cpp main.cpp
test.o main.o
g++ -c test.cpp
test.cpp:8:6: error: redefinition of 'template<class T> void test(T)'
void test(T t)
          ^~~~
In file included from test.h:7,
from test.cpp:4:
test.cpp:8:6: note: 'template<class T> void test(T)' previously declared here
void test(T t)
          ^~~~
make: *** [Makefile:10: test.o] Error 1

修改test.cpp增加条件编译

#ifndef TEST_CPP_
#define TEST_CPP_
#include "test.h"
#include <iostream>

template<typename T>
void test(T t)
{
    std::cout << "it's a template test.." << std::endl;
}
#endif

编译结果:
test.cpp main.cpp
test.o main.o
g++ -c test.cpp
g++ -c main.cpp
g++ -o main test.o main.o

编译成功

运行结果:

./main

it's a template test..

如果模板特化,需要将特化函数声明为内联,否则编译也会报错

main.cpp:(.text+0x0): multiple definition of `void test<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)'; test.o:test.cpp:(.text+0x0): first defined here

test.h

#ifndef TEST_H_
#define TEST_H_
#include <string>
template <typename T>
void test(T t);

template<>
inline void test<std::string>(std::string s);
#include "test.cpp"

#endif

test.cpp

#include "test.h"
#include <iostream>

template<typename T>
void test(T t)
{
    std::cout << "it's a template test.." << std::endl;
}

template<>
void test<std::string>(std::string s)
{
    std::cout << "it's a template special test.." << std::endl;
}
main.cpp
#include "test.h"

int main()
{
    test(1);
    test(std::string("1"));
    return 0;
}
运行结果:
./main
it's a template test..
it's a template special test..

参考:
C++学习笔记 模板 包含编译模式 分别编译模式
Makefile简单编写实例
 
喜欢 0
分享