3

Before posting this question I've read hundreds of Google search result pages, searching solution of this problem in vain. My program can't be more simple — these are the only 3 files:

test.h

#ifndef SYMBOL
#define SYMBOL 

#include <stdio.h>

void output(void);

#endif      

test.c

#include "test.h"

void output(void)
{
  printf("%s\n", "Hello world");
}

untitled.c

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

void main()
{
  output();
  return;
}

I use terminal and enter the following command to compile:

gcc -o aaa untitled.c

Output should print the "Hello world", but instead it keeps throwing this error:

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

I spent the whole day searching for solution, tried all the suggestions as possible but none helped.

Something notable: If I change the file included in untitled.c (#include "test.h" to #include "test.c"), compiler goes without problem.

Can someone please explain to me why, and how to resolve it?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Merkurial
  • 242
  • 3
  • 17

1 Answers1

4

You have to compile and link both source files into the executable; the linker is telling you it cannot find the output() function defined in test.c:

$ gcc -o aaa untitled.c test.c
trojanfoe
  • 120,358
  • 21
  • 212
  • 242
  • Hey thank you a lot you saved me from wasting days in vain :D – Merkurial Apr 15 '15 at 12:41
  • By the way, I saw that gcc on other platform can automatically link header files to compile, it means that by using "gcc -o aaa untitled.c" only it can automatically compile test.c. Typing all the source files to compile may be quite troublesome, is there a shortcut to avoid typing all the source files for the compiler to compile? – Merkurial Apr 15 '15 at 12:43
  • @Merkurial I don't believe that's true and I've never come across it. Nobody likes typing that stuff on the command line and nobody does as everyone will use a build system, the most common of which is `make`. A build system will automatically compile and link whatever is necessary when a source file changes. Other build systems exist; for example `scons`. Alternatively drop the command line and start working with `Xcode`; it's completely free and is the best IDE I've ever used on any platform, including Visual Studio. – trojanfoe Apr 15 '15 at 12:50