Francis
Francis

Reputation: 949

C++ #include not working

I'm trying to include a function like this in C++ and I can't understand why it's not working. I have 3 files.

test.cc

int test() {
  std::cout << "This is a test" << std::endl;
}

test.h

int test();

main.cc

#include "test.h"

int main() {

    test();
    return 0;
}

This is the error I got and the command I used.

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

Upvotes: 0

Views: 20377

Answers (4)

Marco
Marco

Reputation: 131

Assuming you are using your compiler properly, try to include "test.h" on the top of your test.cc file:

#include "test.h"

int test() {
   std::cout << "This is a test" << std::endl;
}

Compile with:

g++ main.cc test.cc -o main

Upvotes: 3

user3813353
user3813353

Reputation: 174

Here's the culprit.

c++ main.cc -o main

You need to link test.o.

c++ main.cc test.cc -o main

Upvotes: 6

Vlad from Moscow
Vlad from Moscow

Reputation: 311126

The definition of function test has undefined behaviour because it does not return a value though it has return type int

int test() {
  std::cout << "This is a test" << std::endl;
}

As you did not report what is the error I think that the problem is that you did not include in the project file test.cc. You have to link it along with file main.cc that the linker would be able to find the definition of test.

Upvotes: 1

Ranic
Ranic

Reputation: 486

You should add the following to test.cc:

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

And make sure you're building/linking with test.cc

Upvotes: 2

Related Questions