1

I'm learning C++, I have gotten to the point that this works:

helloworld.cpp

#include <iostream>
using namespace std;

int main() {
   cout << "Hi" << endl;
   return 0;
}

I am using MacOS Mojave and for compilation I use the commands

>> g++ helloworld.cpp
>> ./a.out

This if working fine. Now I want to use header files. Therefore I've created the following files:

test.cpp

#include <iostream>
#include "add.h"
using namespace std;

int main() {
   add(4,7);
   return 0;
}

add.h

#pragma once
int add(int a, int b);

add.cpp

#include "add.h"
int add(int a, int b) {
    return a + b;
}

and When I try to compile this I get:

>> g++ test.cpp
Undefined symbols for architecture x86_64:
  "add(int, int)", referenced from:
      _main in test-ebc106.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Does anyone have an idea on how to solve this?

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
wohe1
  • 755
  • 7
  • 26

1 Answers1

2
g++ test.cpp add.cpp

Every cpp file needs to be compiled to separate .obj files

Prodigle
  • 1,757
  • 12
  • 23