#Why am I getting an undefined reference error?

14 messages · Page 1 of 1 (latest)

exotic tide
#

utility.h

#define __UTILITY_H__

std::string lowerStr(const std::string& str);
template <typename TP> std::time_t to_time_t(const TP tp);

#endif```
**utility.cpp**
```#include <iostream>
#include <string>
#include <set>

#include <chrono>

#include "utility.h"

std::string lowerStr(const std::string& str){
    std::string result = str;
    std::string::iterator itr = result.begin();
    while (itr != result.end()){
        if (!isdigit(*itr) && !isalpha(*itr)){
            itr = result.erase(itr);
        }
        else{
            if (isalpha(*itr)){
                *itr = tolower(*itr);
            }
            itr++;
        }
    }
    return result;
}

template <typename TP>
std::time_t to_time_t(const TP tp){
    using namespace std::chrono;
    auto sctp = time_point_cast<system_clock::duration>
                (tp - TP::clock::now() + system_clock::now());
    return system_clock::to_time_t(sctp);
}```
`main.cpp` not included, but the code calls upon both lowerStr() and to_time_t(). However, when I compile using `g++ main.cpp utility.cpp -o main.exe -g -Wall -Wextra`, I get an undefined reference error only for to_time_t() and can't figure out why. Probably a dumb issue but I would greatly appreciate if someone could clear this up to me.
random ploverBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

ashen river
#

You have a template defined in a .cpp file, common practice is to put them in the header entirely

#

The compiler needs to see the definition so it can substitute the typed properly

exotic tide
#

template functions should always be implemented in header files?

ashen river
#

Yes

#

Don't worry about ODR with templates, I believe there's some kind of exemption

exotic tide
#

ty for the clarification!

#

sorry but whats ODR?

ashen river
#

One definition rule

#

Every function must only be defined once

exotic tide
#

ah okok

#

thank you very much lol

#

!solved