Linker returns “relocation has an invalid symbol at symbol index…”

后端 未结 5 1884
伪装坚强ぢ
伪装坚强ぢ 2020-12-08 00:03

I am trying out some code on Ubuntu. I\'m trying to run the following code

#include 
#include 

        
相关标签:
5条回答
  • 2020-12-08 00:25

    I'm not sure about your invalid relocation errors but the obvious thing missing is that you have no main function. You need to define an entry point to your application called main, defined at global scope such as:

    int main()
    {
        // TODO: implementation
    }
    
    0 讨论(0)
  • 2020-12-08 00:27

    I just faced this same thing when linking in gtest with CMake and including a file that included a main function.

    So, if you're sure you have a main, and you're linking something -- make sure you don't have two int main()s!

    Simple solution was to split the main() into main.cpp and not link it with the test sources.

    0 讨论(0)
  • 2020-12-08 00:36

    The "undefined reference to 'main'" is because you did not define a main() function, which is the entry point of your program:

    int main()
    {
      // call other functions
    }
    
    0 讨论(0)
  • 2020-12-08 00:38

    Interestingly, I get the same error if I try to compile a .h file instead of a .c file, and link against a library, all in one step.

    Here is a greatly reduced example:

    $ echo 'int main () {}' > test.h
    $ g++ test.h -ltommath && echo success
    /usr/lib/gcc/x86_64-linux-gnu/4.8/../../../x86_64-linux-gnu/crt1.o: In function `_start':
    (.text+0x20): undefined reference to `main'
    collect2: error: ld returned 1 exit status
    

    In this case, the solution is to rename the file to end with .c:

    $ echo 'int main () {}' > test.c
    $ g++ test.c -ltommath && echo success
    success
    
    0 讨论(0)
  • 2020-12-08 00:45

    You have typed wrong command for g++. You should have typed something like:

    g++ file_name random.cpp
    

    You need to name output file. Otherwise it's like "g++ syntax error".

    0 讨论(0)
提交回复
热议问题