Compiling template function

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Nafai

    Compiling template function

    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.


  • Martin Gieseking

    #2
    Re: Compiling template function

    > //function.h[color=blue]
    > template <typename T> void function(T*);
    >
    > //function.cpp
    > template <typename T> void function(T* v)
    > {
    > ...
    > }
    >
    > // main.cpp
    > int main()
    > {
    > float v;
    > function(v);
    > }[/color]


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

    Martin

    Comment

    • John Harrison

      #3
      Re: Compiling template function


      "Nafai" <nafai3000@yaho o.es> wrote in message
      news:h76ic.4672 616$uj6.1595953 2@telenews.tele line.es...[color=blue]
      > 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)
      > {
      > ...
      > }
      >[/color]

      All template code should go in header files.

      john


      Comment

      • JKop

        #4
        Re: Compiling template function

        Nafai posted:
        [color=blue]
        > 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.
        >
        >[/color]


        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

        Comment

        Working...