g++ link problems: In function `_start': (.text+0x20): undefined reference to `main'

36,582

As far as I can see you are not compiling file proj1_unittest.cpp (as your code comment has it) / proj1_unittest.c (as your console output implies).

Share:
36,582
Homunculus Reticulli
Author by

Homunculus Reticulli

Updated on August 16, 2020

Comments

  • Homunculus Reticulli
    Homunculus Reticulli over 3 years

    I am getting an undefined reference to main error - even though I have defined main, and (AFAICT), I have linked it correctly. Here is my code and the commands I used:

    // ################################################
    //proj1.h
    #ifndef  __SCRATCH_PROJ1_H
    #define  __SCRATCH_PROJ1_H
    
    int addOne(int i);
    
    #endif /*__SCRATCH_PROJ1_H */
    
    // ################################################
    
    //proj1.cpp
    #include "proj1.h"
    
    int addOne(int i){
        return i+1;
    }
    
    
    // ################################################
    //proj1_unittest.cpp
    
    #include "proj1.h"
    #include "gtest/gtest.h"
    
    // Test Function
    TEST(addOneTest, Positive) {
        EXPECT_EQ(1,addOne(0));            
        EXPECT_EQ(2,addOne(1));            
        EXPECT_EQ(40320, addOne(40319));   
    }
    
    TEST(addOneTest, Negative) {
        EXPECT_FALSE(addOneTest(-1));      
    }
    
    
    GTEST_API_ int main(int argc, char **argv) {
      testing::InitGoogleTest(&argc, argv);
      return RUN_ALL_TESTS();
    }
    

    Here is the console output:

    $ g++ -isystem -pthread -c ${SOURCE_DIR}/proj1.c -o ${SOURCE_DIR}/proj1.o
    $ g++ -o ${SOURCE_DIR}/mytest ${SOURCE_DIR}/*.o -L${GTEST_DIR} libgtest.a 
    /usr/lib/gcc/x86_64-linux-gnu/4.6/../../../x86_64-linux-gnu/crt1.o: In function `_start':
    (.text+0x20): undefined reference to `main'
    collect2: ld returned 1 exit status
    

    Why is the main() function not been found by the linker?

  • Homunculus Reticulli
    Homunculus Reticulli over 10 years
    Yup, I forgot to compile the .cpp file which contained the main :(