0

I'm trying to do a test of basic linking for cpp files, I've been searching all over and am having a lot of trouble trying to find a solution. I understand that I have to include the header in both cpp's, but I'm having trouble trying to run these two together.

//testMain.cpp

#include <iostream>
#include <stdio.h>
#include "func.h"

using namespace Temp;

int main()
{
    getInfo();
    return 0;
}
//func.h

#ifndef FUNC_H
#define FUNC_H

#include <iostream>
#include <stdio.h>


namespace Temp{
int getInfo();
}


#endif
//functions.cpp
#include "func.h"

using namespace std;

int Temp::getInfo()
{

    return 5 + 6;
}
//error that I'm getting using VS Code
cd "/Users/jcbwlsn/Downloads/Coding/CPP/Workspace/RPG Project/src/" && g++ testMain.cpp -o testMain && "/Users/jcbwlsn/Downloads/Coding/CPP/Workspace/RPG Project/src/"testMain
Undefined symbols for architecture x86_64:
  "Temp::getInfo()", referenced from:
      _main in testMain-1f71a1.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
  • 1
    Does this answer your question? [What is an undefined reference/unresolved external symbol error and how do I fix it?](https://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix) You don't compile function.cpp – 273K May 23 '20 at 08:08
  • In particular, [this answer](https://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix/12574400#12574400). – JaMiT May 23 '20 at 08:13
  • You should compile all the cpp files not only testMain.cpp, e.g. `g++ testMain.cpp functions.cpp -o testMain` – dewaffled May 23 '20 at 09:20

1 Answers1

0

You're supposed to specify all translation unit files when linking a C++ program.

Your program consists of two source files, testMain.cpp and functions.cpp.

Hence the compile-and-link command should be something like:

g++ testMain.cpp functions.cpp -o testMain

Alternatively you can compile each source into separately and then link them into an executable:

g++ -c testMain.cpp -o testMain.o
g++ -c functions.cpp -o functions.o
g++ testMain.o functions.o -o testMain

Having some kind of a Makefile helps to automate this.

rustyx
  • 80,671
  • 25
  • 200
  • 267