在使用c ++ 11创建静态库时,我认为它在链接期间失败了。
我可以使用How to create a static library with g++?中的信息和普通的c ++创建一个静态库并链接到它,但如果我尝试使用c ++ 11功能执行这些步骤,则在链接期间会失败。
TEST.CPP:
#include <iostream>
#include <vector>
#include "libtestlib.h"
using namespace std;
int main() {
itest n1={{1,2,3,4},
{5,6,7,8},
{9,0,1,2}};
cout << "testing...\n";
test_print(n1);
return 0;
}
libtestlib.h:
#ifndef testlib
#define testlib
#include <vector>
using namespace std;
typedef vector<vector<double>> dtest;
typedef vector<vector<int>> itest;
template <typename testtype>
void test_print(testtype);
#endif
libtestlib.cpp:
#include <iostream>
#include "libtestlib.h"
using namespace std;
template <typename testtype>
void test_print(testtype &t)
{
int m=t.size();
int n=t[0].size();
for(int i=0; i<m; i++) {
for(int j=0; j<n; j++)
cout << t[i][j] << " ";
cout << endl;
}
cout << endl;
}
这是我得到的输出:
$ g++ -std=c++11 -c libtestlib.cpp
$ ar rvs libtestlib.a libtestlib.o
r - libtestlib.o
$ g++ -std=c++11 test.cpp libtestlib.a
/tmp/cccJ7SXZ.o:test.cpp:(.text+0x1af): undefined reference to `void test_print<std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > > >(std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > >)'
/tmp/cccJ7SXZ.o:test.cpp:(.text+0x1af): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `void test_print<std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > > >(std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > >)'
collect2: error: ld returned 1 exit status
由于您似乎支持有限数量类型的操作,因此经典的“Just in it in a header”答案不一定是最好的。
您可以通过为每个实现显式导出符号来充分利用这两个世界,但是将实现委托给库中的模板:
libtestlib.h:
#ifndef testlib
#define testlib
#include <vector>
using namespace std;
typedef vector<vector<double>> dtest;
typedef vector<vector<int>> itest;
void test_print(dtest&);
void test_print(itest&);
libtestlib.cpp:
#include <iostream>
#include "libtestlib.h"
using namespace std;
namespace {
template <typename testtype>
void test_print_impl(testtype &t)
{
int m=t.size();
int n=t[0].size();
for(int i=0; i<m; i++) {
for(int j=0; j<n; j++)
cout << t[i][j] << " ";
cout << endl;
}
cout << endl;
}
}
void test_print(dtest& val) {
test_print_impl(val);
}
void test_print(itest& val) {
test_print_impl(val);
}
请注意,对于像这样的小功能,它可能不值得付出努力,只需在标题中内联模板代码就可以了。在什么时候,函数的复杂性及其依赖性的范围保证这是一个判断调用。
在评论中提出对此问题的评论请求,因为代码在评论中看起来非常难看。结合libtestlib.h和libtestlib.cpp
#ifndef testlib
#define testlib
#include <vector>
#include <iostream>
using namespace std;
typedef vector<vector<double>> dtest;
typedef vector<vector<int>> itest;
template <typename testtype>
void test_print(testtype &t)
{
int m=t.size();
int n=t[0].size();
for(int i=0; i<m; i++) {
for(int j=0; j<n; j++)
cout << t[i][j] << " ";
cout << endl;
}
cout << endl;
}
#endif