0

Started using C++ a few days ago and having some trouble wrapping my head around header files. I have the following code divided into three files:

main.cpp

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

int main() {
    Config config;
    config_init(config);
    cout << config.skills << endl;
    cout << config.abilities << endl;
    return 0;
}

Then:

config.h

#ifndef TEST_CONFIG_H
#define TEST_CONFIG_H

struct Config {
    float skills;
    float abilities;
};

void config_init(Config& c);

#endif //TEST_CONFIG_H

and:

config.cpp

#include "config.h"

void config_init(Config& c) {
    c.skills =  5;
    c.abilities = 10;
}

Before subdividing the code in different files everything worked fine. However since I tried using header files I get the following error:

Undefined symbols for architecture x86_64:
  "config_init(Config&)", referenced from:
      _main in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

My suspicion is that there is something wrong in the declaration of the header file and the use of the reference but I don't know how to solve it.

jatrp5
  • 31
  • 3
  • 1
    Did you compiled and linked config.o too? Like `g++ *.cpp` – János Roden Aug 05 '20 at 12:38
  • The message says that the error occurs at link time. That means that you could successfully compile, but failed to pass both compilation units to the linker. How are you building the executable? With `make`? With an IDE? Directly with `cc` or `c++`? Or ... We cannot help you to fix the problem if we do not know what you do. – Serge Ballesta Aug 05 '20 at 12:43
  • I do: `g++ -c *.cpp`, `g++ *.o -o a.out`, and `./a.out` to run it. More info on the compiler `Apple clang version 11.0.0 (clang-1100.0.33.16) Target: x86_64-apple-darwin19.3.0 Thread model: posix`. It's the default Xcode version – jatrp5 Aug 05 '20 at 13:00
  • `*.cpp` is probably not the right approach as I think the files might need to be compiled in the right order to link correctly – Alan Birtles Aug 05 '20 at 13:05
  • should I go for a make file then? – jatrp5 Aug 05 '20 at 13:07
  • @jatrp5 I have almost the same setup like you and it just went well with your files and commands... Can you try on different environment? – János Roden Aug 05 '20 at 13:12
  • @AlanBirtles -- it doesn't matter what order the source files are compiled in. They're independent of each other. – Pete Becker Aug 05 '20 at 13:14
  • @PeteBecker OK, compiling multiple source files isn't something I ever do, just assumed they followed the same linking rules as libraries – Alan Birtles Aug 05 '20 at 13:16
  • @AlanBirtles -- every object file gets linked in; libraries are, indeed, different. – Pete Becker Aug 05 '20 at 13:17

0 Answers0