我正在寫一些代碼,我想發佈爲.h文件和靜態庫。代碼是使用C++模板編寫的,在.cpp文件中定義時使用.h文件中的類聲明。我使用了「顯式實例化」技巧,可以將代碼編譯到靜態庫中。明確的實例化被添加到.cpp文件的末尾。我寫了一些代碼來測試這個庫。它在macos和windows上工作正常,但在ubuntu上它返回「未定義參考」鏈接錯誤。看起來「顯式實例化」技巧在Ubuntu上不起作用。有人知道爲什麼嗎?C++類模板明確實例化工作在macos上,不能在Ubuntu上工作
ubuntu的g ++版本是4.5.3。
編輯
這是模板類的.h文件:
#ifndef PHYSIKA_CORE_MATRICES_MATRIX_2X2_H_
#define PHYSIKA_CORE_MATRICES_MATRIX_2X2_H_
#include "Physika_Core/Utilities/global_config.h"
#include "Physika_Core/Matrices/matrix_base.h"
namespace Physika{
template <typename Scalar>
class Matrix2x2: public MatrixBase<Scalar,2,2>
{
public:
Matrix2x2();
Matrix2x2(Scalar x00, Scalar x01, Scalar x10, Scalar x11);
~Matrix2x2();
inline int rows() const{return 2;}
inline int cols() const{return 2;}
Scalar& operator() (int i, int j);
const Scalar& operator() (int i, int j) const;
Matrix2x2<Scalar> operator+ (const Matrix2x2<Scalar> &) const;
//other operation declarations
//omitted here
};
//overriding << for Matrix2x2
template <typename Scalar>
std::ostream& operator<< (std::ostream &s, const Matrix2x2<Scalar> &mat)
{
s<<mat(0,0)<<", "<<mat(0,1)<<std::endl;
s<<mat(1,0)<<", "<<mat(1,1)<<std::endl;
return s;
}
} //end of namespace Physika
#endif //PHYSIKA_CORE_MATRICES_MATRIX_2X2_H_
模板類的.cpp文件都按:
#include "Physika_Core/Matrices/matrix_2x2.h"
namespace Physika{
template <typename Scalar>
Matrix2x2<Scalar>::Matrix2x2()
{
}
template <typename Scalar>
Matrix2x2<Scalar>::Matrix2x2(Scalar x00, Scalar x01, Scalar x10, Scalar x11)
{
#ifdef PHYSIKA_USE_EIGEN_MATRIX
eigen_matrix_2x2_(0,0) = x00;
eigen_matrix_2x2_(0,1) = x01;
eigen_matrix_2x2_(1,0) = x10;
eigen_matrix_2x2_(1,1) = x11;
#endif
}
//other operation definitions
//omitted here
//explicit instantiation of template so that it could be compiled into a lib
template class Matrix2x2<float>;
template class Matrix2x2<double>;
} //end of namespace Physika
測試代碼是一樣:
#include <iostream>
#include "Physika_Core/Matrices/matrix_2x2.h"
using namespace std;
using Physika::Matrix2x2;
int main()
{
cout<<"Matrix2x2 Test"<<endl;
Matrix2x2<double> mat_double(2.0,1.0,1.0,2.0);
cout<<"A 2x2 matrix of double numbers:"<<endl;
cout<<mat_double;
return 0;
}
錯誤信息是:
g++ -Wall -Wno-write-strings -O2 -I ../../Public_Library/include -L ../../Public_Library/lib -l matrices matrix2x2_test.cpp -o matrix2x2_test
/tmp/ccUrtwwf.o: In function `main':
matrix2x2_test.cpp:(.text+0x91): undefined reference to `Physika::Matrix2x2<double>::Matrix2x2(double, double, double, double)'
matrix2x2_test.cpp:(.text+0x1b9): undefined reference to `Physika::Matrix2x2<double>::Matrix2x2(double, double, double, double)'
//more moitted here
collect2: ld returned 1 exit status
make: *** [matrix2x2_test] Error 1
我想你希望我們解決這個問題而不看你的代碼或錯誤信息? – JBentley
@ JBentley,我編輯了這個問題。對於之前的版本抱歉,我沒有說清楚。 –
謝謝。請提供以下附加信息:'.cpp'文件中'Matrix2x2'的模板構造函數定義,鏈接器給出的完全錯誤消息副本+粘貼,以及您用於執行compile +鏈接的命令。我懷疑在Ubuntu場景中鏈接器不會被正確地指向靜態庫。 – JBentley