Saturday, 20 January 2018
c++ - Why do I get "unresolved external symbol" errors when using templates?
Answer
Answer
When I write C++ code
for a class using templates and split the code between a source (CPP) file and a header
(H) file, I get a whole lot of "unresolved external symbol" errors when it comes to
linking the final executible, despite the object file being correctly built and included
in the linking. What's happening here, and how can I fix it?
Answer
Templated classes and functions are not
instantiated until they are used, typically in a separate .cpp file (e.g. the program
source). When the template is used, the compiler needs the full code for that function
to be able to build the correct function with the appropriate type. However, in this
case the code for that function is detailed in the template's source file and hence
unavailable.
As a result of all this
the compiler just assumes that it's defined elsewhere and only inserts the call to the
templated function. When it comes to compile the template's source file, the specific
template type that is being used in the program source isn't used there so it still
won't generate the code required for the function. This results in the unresolved
external symbol.
The solutions available for
this are to:
- include the
full definition of
the member function in the
template's header file
and not have
a source file for the
template, define all the member functions
in
the template's source file as
"inline"
(Update: [this does not work on Visual Studio 2017+]),
ordefine the member(Update: href="http://www.parashift.com/c++-faq/separate-template-fn-defn-from-decl-export-keyword.html"
functions in
the template's source
with the "export" keyword.
Unfortunately this
isn't supported
by a lot of compilers.
rel="nofollow noreferrer">this has been removed from the standard as of
C++11.)
Both 1
and 2 basically address the problem by giving the compiler access to the full code for
the templated function when it is attempting to build the typed function in the program
source.
php - file_get_contents shows unexpected output while reading a file
I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...
-
I have an app which needs a login and a registration with SQLite. I have the database and a user can login and register. But i would like th...
-
I got an error in my Java program. I think this happens because of the constructor is not intialized properly. My Base class Program public ...
-
I would like to use enhanced REP MOVSB (ERMSB) to get a high bandwidth for a custom memcpy . ERMSB was introduced with the Ivy Bridge micro...
No comments:
Post a Comment