简体   繁体   中英

How to use extern to link to a function in other cpp file?

Here is my main.cpp:

#include <iostream>
#include "function.cpp"

using namespace std;

extern int giveMain();

int main() {
    int x = 4;
    x = giveMain(x);
    cout << x << endl;
}

And here is my function.cpp:

#include <iostream>

using namespace std;

int giveMain(int a) {
    a = 3 + a;
    return a;
}

But when I compile, it says that "Linker command failed". Can anyone helps me to solve this problem.

You declared the function int giveMain() in main.cpp but the function in function.cpp takes an int . Declare the correct function and it should work. Also extern is the default for functions so you don't need to include the keyword.

EDIT: Just noticed that you #include <function.cpp> in main.cpp. Never include .cpp files. The issue you were having was multiple definitions for int giveMain(int) because the contents of functions.cpp was being compiled twice.

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