dimanche 8 janvier 2023

C++: Undefined symbols for architecture arm64 ... linker command failed

I have the following files,

my.h

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

my.cpp

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

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

void print(int i) {
  std::cout << i << '\n';
}

use.cpp

#include "./headers/my.h"

int main() {
  foo = 7;
  print_foo();
  print(99);
}

building gives the following error,

/> g++ -W -std=c++11 -o output *.cpp 
Undefined symbols for architecture arm64:
  "_foo", referenced from:
      print_foo() in my-e8b938.o
      _main in use-318772.o
     (maybe you meant: print_foo())
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Tried removing each definition and its references one by one and testing. It compiles fine when

void print(int)

and its references are alone. The other two defintions give a similar error shown above.

My environment: Mac M1 (Monterey), VSCode, g++ v.14

New to C++. What's going on? How do I correct?

Aucun commentaire:

Enregistrer un commentaire