I'm having a weird problem compiling a function when I try using multiple files. I've boiled it down to this simple example: suppose I want to find the sum of a vector of integers. If I try compiling the following code, it works as expected:
#include <vector> #include <iostream> using namespace std; int VectorSum (const vector<int>& values) { int S = 0; for (int t=0; t < values.size(); t++) { S += values[t]; } return S; } int main() { vector<int> values; values.push_back(-100); values.push_back(75); values.push_back(75); cout << "Total = " << VectorSum(values) << endl << endl; cin.ignore(1, '\n'); return 0; } However, if I try using a header file, it crashes on my (error C4430 when compiling on VS 2010 for Windows XP). Here's the code for the other approach:
the header:
/* VectorSum.h */ #pragma once #include <vector> int VectorSum (const vector<int>& values); the source:
/* VectorSum.cpp */ #include "VectorSum.h" #include <vector> int VectorSum (const vector<int>& values) { int S = 0; for (int t=0; t < values.size(); t++) { S += values[t]; } return S; } the implementation:
/* Main.cpp */ #include "VectorSum.h" #include <vector> #include <iostream> using namespace std; int main() { vector<int> values; values.push_back(-100); values.push_back(75); values.push_back(75); cout << "Total = " << VectorSum(values) << endl << endl; cin.ignore(1, '\n'); return 0; } As you can see, the code for the function in VectorSum.cpp is identical to the code in my first .cpp file, so the problem must be in the header. Any ideas what I'm doing wrong?
std::accumulate (values.begin (), values.end (), 0);...