I'm fairly new to c++ and programming in general and was watching the free tutorial on the freecodecamp.org youtube channel and when I got up to the point where I used multiple c++ files, I got multiple compiler errors with g++ and clang.
Here is main.cpp
#include <iostream> #include "compare.h" int main(){ int maximum = max(134,156); std::cout << "max : " << maximum << std::endl; return 0; } This is compare.cpp:
int max( int a, int b){ if(a>b) return a; else return b; } And the compare.h file
int max( int a, int b);//Declaration When I try and build with clang I get:
Undefined symbols for architecture arm64: "max(int, int)", referenced from: _main in main-e30ba6.o ld: symbol(s) not found for architecture arm64 clang-13: error: linker command failed with exit code 1 (use -v to see invocation)
When I build with g++ I get:
Undefined symbols for architecture arm64: "__Z3maxii", referenced from: _main in cc3V4eOt.o ld: symbol(s) not found for architecture arm64 collect2: error: ld returned 1 exit statu
I've searched all over youtube and stack overflow and the only solution I found was to link the files with
g++ main.cpp compare.cpp -o main But this only worked once and never again. Any help would be greatly appreciated thanks!
Edit
After some more research the only thing that gave me a definitive answer was to build with clang, get the error, then run:
clang++ main.cpp compare.cpp -o main
But I have to do this every time I make changes to the code and that just seems tedious and there has to be a better way. Also if I were to have multiple .cpp files I would have to run those into the command as well.
