Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linking Error due to symbol(s) not found in Bjarne Stroustrup "Programming and Practices using c++"

I'm new to c++ (and compiled languages in general) and am doing the drill at the end of chapter 8 in Bjarne Stroustrup "Programming and Practices using c++" but I'm getting the following error when I try to compile the code

➜  Desktop g++ -std=c++11 *.cpp -o use
Undefined symbols for architecture x86_64:
  "_foo", referenced from:
      print_foo() in my-4f7853.o
      _main in use-46cb26.o
     (maybe you meant: __Z9print_foov)
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I've also tried using g++ -c my.cpp use.cpp followed by g++ -o use.exe my.o use.o but this gave the same error. The other approach I tried was g++ -c use.cpp -o use.exe, however use.exe produced no output when it ran. The source code files are

my.h

extern int foo;
void print_foo();
void print_int(int);

my.cpp

#include "my.h"
#include <iostream>

void print_foo() {
  std::cout << foo << '\n';
}

void print_int(int num) {
  std::cout << num << '\n';
}

use.cpp

#include "my.h"
#include <iostream>

int main() {

  std::cout<<"DSGFSGFSG"<< '\n';
  foo = 7;
  print_foo();

  int i = 99;
  print_int(i);

}

I've looked at other questions that are similar (if not seemingly the same is in Link-time errors in VS 2013 while compiling the C++ program - B. Stroustrup's PPP using C++: Ch. 8 - Q1 Drill?) but the solutions haven't worked for me. Is the problem to do with my compilation using g++ or have I made a more fundamental error?

like image 762
scabbers Avatar asked Apr 01 '20 10:04

scabbers


1 Answers

The global variable foo is only declared in your header file.
extern int foo;

You also need to define it in my.cpp
int foo;

The declaration is a promise: "it exists somewhere".
The definition actually reserves some storage for this variable.

So your linker complains because some code relying on this promise needs to access this missing storage.

like image 52
prog-fh Avatar answered Nov 01 '22 17:11

prog-fh