gpt4 book ai didi

c++ - 链接错误 : collect2: error: ld returned 1 exit status

转载 作者:行者123 更新时间:2023-11-28 00:32:48 26 4
gpt4 key购买 nike

我创建了一个名为 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 创建了一个 .o 文件

然后我尝试这样做: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


请帮我解决这个问题。我认为我所做的一切都是正确的。

最佳答案

请注意,days_from_civil 是一个模板函数,这通常意味着您需要为其提供定义,而不仅仅是声明。在头文件中包含函数的主体,你就可以开始了,或者提供一个显式的实例化,比如

template days_from_civil<int>(int y, unsigned m, unsigned d) noexcept;

关于c++ - 链接错误 : collect2: error: ld returned 1 exit status,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22177603/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com