Separate allocate() definition leads to "undefined reference" link error in C++ custom allocator -
this question has answer here:
the code placed in 3 files: test.hpp, test.cpp, another.cpp.
source code test.hpp:
#ifndef test_hpp_ #define test_hpp_ template<typename t> class allocator { public: typedef size_t size_type; typedef ptrdiff_t difference_type; typedef t* pointer; typedef const t* const_pointer; typedef t& reference; typedef const t& const_reference; typedef t value_type; template<typename o> struct rebind { typedef allocator<o> other; }; allocator() {} allocator(const allocator& alloc) {} template<typename o> allocator(const allocator<o>& alloc) {} ~allocator() {} pointer address(reference __x) const { return &__x; } const_pointer address(const_reference __x) const { return &__x; } void construct(pointer p, const t& value) { new ((void *)p) t(value); } void destroy(pointer p) { p->~t(); } pointer allocate(size_type n, const_pointer phint = nullptr);// { return nullptr; } void deallocate(pointer p, size_type size = 0) {} inline size_type max_size() const { return 0; } }; template<typename t> inline bool operator==(const allocator<t>&, const allocator<t>&) { return true; } template<typename t> inline bool operator!=(const allocator<t>&, const allocator<t>&) { return false; } class string : public std::basic_string<wchar_t, std::char_traits<wchar_t>, allocator<wchar_t>> { typedef std::basic_string<wchar_t, std::char_traits<wchar_t>, allocator<wchar_t>> string_type; public: ~string() {} string(const wchar_t* value = l"") : string_type(value, allocator<wchar_t>()) {} }; #endif /* test_hpp_ */
source code test.cpp:
#include <iostream> #include <string> #include <ctime> #include <type_traits> #include <functional> #include <cstddef> #include "test.hpp" #define millis(time) (clock() - time) * 1000 / clocks_per_sec int main() { string string = l"ok"; return 0; }
source code another.cpp:
#include <iostream> #include <string> #include <ctime> #include <type_traits> #include <functional> #include <cstddef> #include "test.hpp" template<typename t> t* allocator<t>::allocate(size_t n, const t* phint) { return nullptr; }
compiled them got linkage error: test.cpp:(.text.startup+0x95): undefined reference `allocator::allocate(unsigned long, char const*)'
however, if move code body in another.cpp test.hpp, this:
pointer allocate(size_type n, const_pointer phint = nullptr) { return nullptr; }
compilation successful. since custom allocator::allocate() complex, inconvenient placing code body test.hpp header file.
does give me suggestions? thanks.
the compiler cannot know implementation is. since test.hpp defines methods, compiler expects implementation in test.cpp. clean way structure in opinion. however, if absolutely needed, might around individually compiling , cleverly linking obj files in right order. consider rather dirty.
Comments
Post a Comment