My code is:
test.cpp
#include<iostream>
#include<boost/bind.hpp>
#include "extern.h"
using namespace std;
using namespace boost;
int fun(int x,int y){return x+y;}
/*
*void add(int &m,int &n);
*/
int main(){
int m=1;int n=2;
cout << m << " "<< n << endl;
add(m,n);
cout << m << " "<< n << endl;
return 0;
}
extern.h:
#include<iostream>
#include<boost/bind.hpp>
using namespace std;
using namespace boost;
void add(int &n,int &m);
extern.cpp:
#include<iostream>
#include<boost/bind.hpp>
using namespace std;
using namespace boost;
extern int m;
extern int n;
void add(int &n,int &m) {
n = n+1;
m = m+1;
}
When I compile it with
g++ -Wall -o test test.cpp
It turns out to be:
/tmp/ccMHVRNo.o: In function `main':
test.cpp:(.text+0x7b): undefined reference to `add(int&, int&)'
collect2: ld returned 1 exit status
But when I compile it with:
g++ -Wall -o test test.cpp extern.cpp
It works well:
$ ./test
1 2
2 3
So the reason is that test.cpp
can't find the implementation of the add()
function.
But I have added extern.h
to test.cpp
, why does it still say "undefined reference to add(int&, int&)
"?