Compiling template function

Discussion in 'C++' started by Nafai, Apr 23, 2004.

  1. Nafai

    Nafai Guest

    Hello I get linker error with files like these:

    //function.h
    template <typename T> void function(T*);

    //function.cpp
    template <typename T> void function(T* v)
    {
    ...
    }

    // main.cpp
    int main()
    {
    float v;
    function(v);
    }

    g++ -o main main.o function.o <-- Linker error.
     
    Nafai, Apr 23, 2004
    #1
    1. Advertising

  2. > //function.h
    > template <typename T> void function(T*);
    >
    > //function.cpp
    > template <typename T> void function(T* v)
    > {
    > ...
    > }
    >
    > // main.cpp
    > int main()
    > {
    > float v;
    > function(v);
    > }



    Move the implementation of the template function to the header file so the
    compiler can see it in main.cpp.

    Martin
     
    Martin Gieseking, Apr 23, 2004
    #2
    1. Advertising

  3. "Nafai" <> wrote in message
    news:h76ic.4672616$...
    > Hello I get linker error with files like these:
    >
    > //function.h
    > template <typename T> void function(T*);
    >
    > //function.cpp
    > template <typename T> void function(T* v)
    > {
    > ...
    > }
    >


    All template code should go in header files.

    john
     
    John Harrison, Apr 23, 2004
    #3
  4. Nafai

    JKop Guest

    Nafai posted:

    > Hello I get linker error with files like these:
    >
    > //function.h
    > template <typename T> void function(T*);
    >
    > //function.cpp
    > template <typename T> void function(T* v)
    > {
    > ...
    > }
    >
    > // main.cpp
    > int main()
    > {
    > float v;
    > function(v);
    > }
    >
    > g++ -o main main.o function.o <-- Linker error.
    >
    >



    Well, first thing that strikes me: Include "function.h" in
    "main.cpp"!

    #include "function.h"


    Secondly, the entire template goes into the header file. Why? Because
    it's dealt with entirely by the compiler, NOT the linker!

    -JKop
     
    JKop, Apr 23, 2004
    #4
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Robert Allan Schwartz
    Replies:
    1
    Views:
    419
    Victor Bazarov
    Aug 9, 2004
  2. Jim West
    Replies:
    3
    Views:
    784
    Jim West
    Oct 7, 2004
  3. Replies:
    4
    Views:
    503
    Rob Williscroft
    Nov 18, 2004
  4. Replies:
    2
    Views:
    374
  5. Peng Yu
    Replies:
    3
    Views:
    805
    Thomas J. Gritzan
    Oct 26, 2008
Loading...

Share This Page