0

I am learning c++ and the instructor made a video on how to make classes and functions in multiple files.

I have 3 simple c++ files called "main.cpp", "something.h", and "something.cpp", they are all in the same directory that has no other files. (they are below)

the problem is that the linker is throwing an error message and I really don't know why. (maybe I'm just missing something really obvious)

// main.cpp 

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

int main(){
    int a{2}, b{2};
    std::cout << add(a,b) << std::endl;

    int arr[5] {1,2,4,8,16};

    print_arr(arr, 5);

    std::cout << "Hello, world\n"; 
    return 0;
}
// something.h
#ifndef _SOMETHING_H_
#define _SOMETHING_H_ 

int add(int a, int b);
void print_arr(int* arr, unsigned int size);

#endif // _SOMETHING_H_
// something.cpp
#include "something.h"
#include <iostream>
int add(int a, int b){
     return a+b; 
}

void print_arr(int* arr, unsigned int size){
     std::cout << "{ ";
     for (int i = 0; i < size; i++)
          std::cout << arr << ' ';
     std::cout << '}';
}

the error:

Undefined symbols for architecture x86_64:
  "add(int, int)", referenced from:
      _main in main-06aa98.o
  "print_arr(int*, unsigned int)", referenced from:
      _main in main-06aa98.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
  • Check more of the build output and make absolutely certain that something.cpp is being compiled and linked in. – user4581301 Dec 02 '20 at 05:08
  • I've tried not including the functions and the compiler did not give an error, when I include "add", "print_arr", or both the compiler gives me an error – fawn kitten Dec 02 '20 at 05:08
  • `#define _SOMETHING_H_ ` That identifier is reserved to the language implementation. By defining it, your program will have undefined behaviour. You should use another header guard. – eerorika Dec 02 '20 at 07:22
  • To fill out the comment by @eerorika, names that begin with an underscore followed by a capital letter (`_SOMETHING_H_`) and names that contain two consecutive underscores are reserved for use by the implementation. – Pete Becker Dec 02 '20 at 15:38

1 Answers1

1

At simplest, clang++ -Wall -g something.cpp main.cpp -o main.

You could also compile something.cpp first to create something.o...

clang++ -Wall -g -c something.cpp

...then specify to link with that when compiling main.cpp:

clang++ -Wall -g main.cpp something.o

This last approach scales better, as if you only change main.cpp you can just do the second step without recompiling something.o.

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252