console.cpp:

#include <iostream>
#include <string>
#include <vector>
using namespace std;


template <typename T>
T
#ifndef _DEBUG
	&
#endif
val(const T& x);


class A
{
private:
	
public:
	void f();
};

void A::f()
{
	val(1);// deleting val solves the problem
}

int main()
{
	new A;
	cin.get();
}

general.cpp:

template <typename T>
T
#ifndef _DEBUG
	&
#endif
val(const T& x)
{
	return x;
}

the error:

Error 2 fatal error LNK1120: 1 unresolved externals G:\Important Files\My Documents\Visual Studio 2008\Projects\tack\Debug\tack.exe

I don't understand why my program has errors!?

Dani AI

Generated

Brief answer: the linker error happens because the compiler never emitted a concrete val<int> function for the call in console.cpp. The call there only sees a declaration; the template body lives in another translation unit, and the compiler only generates (instantiates) a templated function where it has the full definition or when an explicit instantiation is requested. This is what was pointing toward.

Two practical fixes:

  • Put the template definition in a header and include it where the template is used. Example:
/* val.h */
template<typename T>
T val(const T& x) { return x; }

/* console.cpp */
#include "val.h"
...
val(1);
  • Keep the definition in a single .cpp but force instantiation for the needed type(s):
/* general.cpp */
#include "val.h"    // or the declaration
template int val<int>(const int&);

Troubleshooting notes and cautions:

  • Ensure all relevant .obj files are actually part of the link. LNK1120 means the symbol was never provided by any object module.
  • Do not change function signatures via macros across translation units. In the posted code _DEBUG changes the return type (value vs reference); compiling TUs with different settings will produce different mangled symbols and break linking.
  • Returning T& while passing an rvalue like 1 will yield a dangling reference — undefined behavior. Prefer returning by value or ensure callers pass lvalues if a reference return is required.
  • For formal details, see the function-template and explicit-instantiation documentation (cppreference): function templates, .

This ties back to 's repro: the unresolved external disappears once the compiler either sees the template body at the call site or a forced instantiation exists.

Recommended Answers

All 3 Replies

I'm deducing templates cannot have external linkage! is that correct?

Near the end of that FAQ was a link to another one:

  1. A template is not a class or a function. A template is a "pattern" that the compiler uses to generate a family of classes or functions.

(More at the link.)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.