简体   繁体   中英

How to link a program in C++

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&) "?

The implementation of the function void add(int&,int&) is in the source file extern.cpp. The compiler can't know that this files is related to the program until you tell it.

You must specify all source files at the command line:

g++ -Wall -o test test.cpp extern.cpp

If you want to avoid compiling of all source files you can also specify the already compiled object file:

g++ -Wall -o test test.cpp extern.o

When you don't want to think every time what commands you need to compile you should use make and create an Makefile with rules that define how the target is build. with the makefile you can just start

make

and get the result.

The header file extern.h only tells your program how the prototype of the function is made. The linker needs the actual implementation of the function, so it looks for the code add(int&,int&) references to, and it cannot find it unless you give to the compiler all the files it needs (in this case, extern.cpp is the file the linker needs when looking for the add function).

This is the usual formula:

g++ -Wall -c test.cpp
g++ -Wall -c extern.cpp
g++ -o test test.o extern.o

There are one-liners, but those don't scale so well to larger projects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM