Search code examples
ccygwinld

ld returned 1 exit status - c file structure


I am editing an open source C project to customize it for my usage. Basically it has the following file structure:

                  |--- /include ----- loremipsum.h
                  |
/loremipsum ----- |--- /ex      ----- loremipsum.c and more
                  |
                  |--- /src     ----- other helpful functions

In loremipsum.h one can find a list of functions that are defined in /src, via

#ifdef __cplusplus
extern "C" {
#endif

but this has not been edited by me, so i suppose it should work.

In loremipsum.c there are:

  • #include "loremipsum.h"
  • plenty of extern void function_defined_in_ex()(1)
  • some more definitions.
  • main

After editing the c-files and trying to recreate a new exefile via

$ gcc  loremipsum.c -o customloremipsum.exe

first I got an error, that loremipsum.h was not found, so I changed the include to "path/to/include/loremipsum.h", I did that in all .c files with that include.

Then, all of the (1) had an error, namely "/usr/lib/gcc/x86_64-pc-cygwin/9.3.0/../../../../x86_64-pc-cygwin/bin/ld: /tmp/ccBt2CkE.o:loremipsum.c:(.text+0x3745): undefined reference to function_defined_in_ex' ld returned 1 exit status". I really can't figure out, why.

I think the first include error is already strange, in my understanding, there should be no problem to find the .h file. Also, I can't figure out, how to make clear where to find the functions in (1).

I'm very sorry for that long post, I'm just afraid, I'm forgetting something fundamental.

I am working on Windows 10 and compiling in a Cygwin shell. Thank you for your help.


Solution

  • You need to tell the compiler where to look for include files using the -I parameter, for example:

    gcc -I../include loremipsum.c -o customloremipsum.exe
    

    Don't specify the full path in the #include lines.

    Any undefined references you get are cause by the linker because the .c files or objects or libraries defining the symbols are not compiled in yet.

    Also, it's better to split compilation and linking steps to help you where things go wring. Like this:

    gcc -c -I../include loremipsum.c -o customloremipsum.o
    gcc customloremipsum.o -o customloremipsum.exe