我创建了一个名为days_from_civil.hpp
的头文件。
#ifndef BOOST_CHRONO_DATE_DAYS_FROM_CIVIL_HPP
#define BOOST_CHRONO_DATE_DAYS_FROM_CIVIL_HPP
namespace boost {
namespace chrono {
template<class Int>
Int
days_from_civil(Int y,unsigned m,unsigned d) noexcept ;
}
}
#endif
档案days_from_civil.cpp
#include<type_traits>
#include<limits>
#include<stdexcept>
#include"days_from_civil.hpp"
namespace boost {
namespace chrono {
template<class Int>
Int
days_from_civil(Int y,unsigned m,unsigned d) noexcept {
static_assert(std::numeric_limits<unsigned>::digits >= 18,
"This algorithm has not been ported to a 16 bit unsigned integer");
static_assert(std::numeric_limits<Int>::digits >= 20,
"This algorithm has not been ported to a 16 bit signed integer");
y -= m <= 2;
const Int era = (y >= 0 ? y : y-399) / 400;
const unsigned yoe = static_cast<unsigned>(y - era * 400); // [0, 399]
const unsigned doy = (153*(m + (m > 2 ? -3 : 9)) + 2)/5 + d-1; // [0, 365]
const unsigned doe = yoe * 365 + yoe/4 - yoe/100 + doy; // [0, 146096]
return era * 146097 + static_cast<Int>(doe) - 719468;
}
}
}
然后我将文件testalgo.cpp
定义为
#include <iostream>
#include "days_from_civil.hpp"
int main(int argc, char const *argv[])
{
int y = 1981;
int m = 5;
int d = 30 ;
int x = boost::chrono::days_from_civil(y,m,d);
std::cout<<x<<std::endl;
return 0;
}
然后我使用g++ -std=c++11 -c days_from_civil.cpp
然后我试着这样做:
g++ -std=c++11 testalgo.cpp days_from_civil.o
但是它给出了这个错误:
/tmp/ccwrTUOn.o: In function `main':
testalgo.cpp:(.text+0x32): undefined reference to `int boost::chrono::days_from_civil(int, unsigned int, unsigned int)'
collect2: error: ld returned 1 exit status
请帮我解决这个问题。 我想我正在做的一切正确。
答案 0 :(得分:3)
请注意days_from_civil
是一个模板函数,通常意味着您需要为它提供一个定义,而不仅仅是声明。在头文件中包含函数的主体,你可以去,或提供一个明确的实例化,如
template days_from_civil<int>(int y, unsigned m, unsigned d) noexcept;