0

I am currently becoming crazy. It seems like there is a problem with gcc and it can't open include files can't find the function DoIt() when linking. I tried compiling this code in code blocks and it didn't work so I tried it with G++ in the console and it still didn't work. So I think it's a problem with gcc.

This is my code

main.cpp

#include <iostream>
#include "source.h"
int main()
{
    std::cout<<"That works"<<std::endl;
    DoIt();
    while(true)
    {
    }
    return 0;
}

source.cpp

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

void DoIt()
{
std::cout<<"That works too"<<std::endl; //Currently doesn't work
}     

source.h

void DoIt();

And this is what I wrote in the terminal

g++ main.cpp -std=c++11 -o result

This is the error message when i run it

/tmp/ccG6X4Bw.o: In function `main':
main.cpp:(.text+0x2d): undefined reference to `DoIt()'
collect2: error: ld returned 1 exit status

I have no clue why it doesn't work

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Binkiklou
  • 1
  • 1
  • 1
    This is not a problem with the include paths, but an error from the linker telling you that you never defined `DoIt`. You need to provide all `.cpp` files to the compiler command line if you compile and link in one invocation (the default without `-c` on the `g++` command line), so that it has all the definitions. –  Dec 04 '18 at 23:32
  • 1
    `g++ main.cpp -std=c++11 -o result` does not look like it compiles and links in source.cpp. Give `g++ main.cpp source.cpp -std=c++11 -o result` a shot. – user4581301 Dec 04 '18 at 23:33

1 Answers1

0

By default, gcc will try to compile and link. Linking without the code from source.cpp will cause the linker to be unable to link the call of DoIt to its code. If you just wish to compile, pass -c to gcc.

From the man page:

  When you invoke GCC, it normally does preprocessing, compilation, assembly and linking.
  ...
   -c  Compile or assemble the source files, but do not link.
       The linking stage simply is not done.
David Schwartz
  • 179,497
  • 17
  • 214
  • 278