简体   繁体   中英

Getting “undefined symbols for architecture” error when separating some functions from main.cpp, what to do?

The story

My main.cpp is getting really cluttered so I decided to separate other functions from it (some helper functions for IO operations in main() ).

The problem

The files compile fine when the functions are within main.cpp . When I put them to a .h - .cpp pair, I get the following compiler error.

The line I use:

g++ -I ./headers/ ./definitions/*.cpp -o main.o main.cpp

The error:

    Undefined symbols for architecture x86_64:
      "void showSettings<double>(std::__1::vector<std::__1::basic_string<char, std::__1::char_traits<char>,
std::__1::allocator<char> >,
std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>,
std::__1::allocator<char> > > > const&,
std::__1::vector<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, 
std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, 
std::__1::allocator<char> > > > const&, int, int, double, double, int, int, int, int, int)", 
referenced from:
          _main in main-7k1oIa.o
    ld: symbol(s) not found for architecture x86_64

The only working solution right now is to bring the functions back to main.cpp . I've included all necessary headers, using namespace std and prepending std:: to vector and string but the error keeps showing.

If it's of any help, the code that appears in the error is:

template <typename inputType>
void showSettings(  const vector<string> &a,
                    const vector<string> &b,
                    int eq,
                    int meth,
                    inputType root1,
                    inputType root2,
                    int sigs,
                    int showPerLoop,
                    int plotRoots,
                    int loopMode,
                    int minLoops)

Templates are only instantiated when called, so if no function in your secondary .cpp file calls showSettings with a <double> , then the function wasn't created.

Generally, you want to leave template functions in a .h file so that the actual definition is visible when needed.

(See also: Why should the implementation and the declaration of a template class be in the same header file? )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM