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

标签 c++ c++11

我创建了一个名为 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/

相关文章:

c++ - lambda 应该能够看到本地类吗?

c++ - 涉及嵌套模板参数和默认值的模板类型推导

c++ - C++11 中的隐式构造函数参数转换

c++ - 在 C++ 中从标量到非标量的转换

c++ - 如何在Qt Creator中创建逻辑目录?

C++ 传递结构地址

c++ - GCC 4.9 中的模板实例化错误,在 GCC 4.8 中工作正常

python - 是否有 C++11 等同于 Python 的 @property 装饰器?

C++11 : unique_ptr complains about incomplete type, 但是当我包装它时不是

c++ - 如何删除文件夹中的所有文件,但不使用 NIX 标准库删除文件夹?