-2

I am trying to break my code into multiple files in c++. My main file is base.cpp in which I am trying to import foo.cpp. But it shows the following error during compilation.

Undefined symbols for architecture x86_64: "foo()", referenced from: _main in base-a3f2f3.o ld: symbol(s) not found for architecture x86_64

My base.cpp file is :

#include<bits/stdc++.h>
#include "foo.h"
using namespace std; 

int main(){
    foo(); 
    cout<<tot<<endl;
    cout<<"bye"<<endl;
}

My foo.cpp is :

#include<bits/stdc++.h>
using namespace std ; 

void foo(){
    cout<<"hello world"<<endl; 
}
int tot = 90;

My foo.h file is:

#ifndef FOO_H
#define FOO_H
int tot; 
void foo(); 

#endif 

I use the following command to compile my c++ files successfully : g++ -std=c++14 filename.cpp && ./a.out

I use Mac. My code editor is VS Code.

My cpp configuaration is as follows : 
{
"configurations": [
        {
            "name": "Mac",
            "includePath": [
                "${workspaceFolder}/**"
            ],
            "defines": [],
            "macFrameworkPath": [
                "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks"
            ],
            "compilerPath": "/usr/bin/clang",
            "cStandard": "c11",
            "cppStandard": "c++17",
            "intelliSenseMode": "clang-x64"
        }
    ],
    "version": 4
}

Thanks.

drescherjm
  • 10,365
  • 5
  • 44
  • 64
  • 1
    Does this answer your question? [What is an undefined reference/unresolved external symbol error and how do I fix it?](https://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix) – Alan Birtles Nov 30 '19 at 13:19
  • But I am not able to find how to compile my code? – Siddharth Goyal Nov 30 '19 at 13:25

1 Answers1

1

You have to compile all cpp files:

g++ -std=c++14 base.cpp foo.cpp && ./a.out

It's not part of the problem but you should avoid #include<bits/stdc++.h>. It's an implementation defined header

Thomas Sablik
  • 16,127
  • 7
  • 34
  • 62
  • Thanks. It works. But suppose I want to declare a global variable in foo.cpp and use in base.cpp. How to do this? I am getting duplicate symbol error. – Siddharth Goyal Nov 30 '19 at 13:33
  • @SiddharthGoyal `int tot;` is a definition, not a declaration. A global variable can only be defined once. To declare `tot` you can `extern int tot;` in `foo.h` and you have to define it in one cpp file. – Thomas Sablik Dec 01 '19 at 00:17