How to fix linker error with function template?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • bajajv
    New Member
    • Jun 2007
    • 152

    How to fix linker error with function template?

    Hi, I am trying to write a function template which takes starting and end addresses for an array and the value to search. But when I call this function, I get linker error 1120 - 1 unresolved external.
    Can you please check what am I doing wrong?

    Code:
    template <typename T>
    bool find(T* first, T* last, T& value)
    {
    	bool result = false;
    
    	if ((first) && (last))
    	{
    		while (first != last)
    		{
    			if (*first == value)
    			{
    				result = true;
    				break;
    			}
    			first++;
    		}
    	}
    	return result;
    }
    
    int main()
    {
    	int arr[] = {1,2,3,4,5};
    	
    	vector<int> vect;
    	vect.push_back(arr[1]);
    	vect.push_back(arr[2]);
    	vect.push_back(arr[3]);
    	vect.push_back(arr[4]);
    	vect.push_back(arr[5]);
    
    	int val_to_check = 3;
    
    	bool result1 = find(arr, arr+4, val_to_check);
    
    	bool result2 = find(&vect[0], &vect[4], val_to_check);
    
    	cout << result1 << " " << result2 << endl;
    
     	return 0;
    }
  • horace1
    Recognized Expert Top Contributor
    • Nov 2006
    • 1510

    #2
    gcc compiles it OK when I add the headers
    Code:
    #include <iostream>
    #include <vector>
    using namespace std;
    a run gives
    Code:
    1 1
    what compiler are you using?

    Comment

    • bajajv
      New Member
      • Jun 2007
      • 152

      #3
      It is working here also now.. it turned out that the implementations were in different file, so the definition was not available.
      After including the definition file, it is working.
      Sorry for the trouble..
      But do I need to include both the .h as well as .cpp files everytime?

      Comment

      • horace1
        Recognized Expert Top Contributor
        • Nov 2006
        • 1510

        #4
        header files usually hold declarations and you include them in any file that uses the constants/classes/functions/externs etc.
        You include the .cpp file that contains the definitions once in the project otherwise you would get identifiers defined multiple times.

        Comment

        • bajajv
          New Member
          • Jun 2007
          • 152

          #5
          thanks horace1.. this solved my error in another function also... :)

          Comment

          Working...