Linker errors with Templates...

This is a discussion on Linker errors with Templates... within the C++ Programming forums, part of the General Programming Boards category; Hi all, I have read that "template classes and functions" must be declared and defined in the same file (in ...

  1. #1
    Beginning game programmer Petike's Avatar
    Join Date
    Jan 2008
    Posts
    64

    Question Linker errors with Templates...

    Hi all,
    I have read that "template classes and functions" must be declared and defined in the same file (in some header file). But I don't want to have the declarations and the definitions in the same file (that is in contrast to what I was learning so long time). Is there any possible solution to have separated the template declarations in header file and the template definitions in .cpp file (without linker errors)?
    Thanks.
    Petike

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    The key here isn't whether something is in the same file or not - it is whether the compiler can see the source code when it compiles or not. You could of course have some of your template code in a .h file, and then include a .cpp file inside that header [or in the main .cpp file]. But I guess that's not what you actually wanted either, so the answer is simply "No, you can't do it any other way".

    The reason is that templates are expanded when the compiler encounters the use of a tempated item. At that point, the compiler must have access to the SOURCE of the template code itself [1], to generate the code for that function.

    [1] Of course, it actually reads all templates and stores them in an internal form, then uses that internal form to generate the functions in the object file.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Beginning game programmer Petike's Avatar
    Join Date
    Jan 2008
    Posts
    64
    Thanks you very much, Mats
    Petike

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Templates + ref to pointer + linker error.
    By Sparrowhawk in forum C++ Programming
    Replies: 8
    Last Post: 05-18-2009, 04:06 PM
  2. Linker errors on Winsock2 functions
    By ShadowMetis in forum C++ Programming
    Replies: 2
    Last Post: 11-20-2004, 10:19 PM
  3. help, linker errors when adding library file to project
    By ngcfan525 in forum C++ Programming
    Replies: 1
    Last Post: 03-09-2003, 01:27 PM
  4. MSVis-Studio C++ libraries and linker errors
    By kellydj in forum Windows Programming
    Replies: 10
    Last Post: 03-12-2002, 01:03 PM
  5. Linker errors with simple static library
    By Dang in forum Windows Programming
    Replies: 5
    Last Post: 09-08-2001, 09:38 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21