Results 1 to 4 of 4

Thread: undefined reference in g++

  1. #1
    Join Date
    Aug 2014
    Beans
    14

    Post undefined reference in g++

    Hello guys,

    I'm quite like a newbie in C++ and Ubuntu, so forgive me if I make some stupid mistakes. I tried compiling these files on Windows (Visual Studio '13) with no problem, file run just fined. Exactly what I'm looking for.

    I switch to Ubuntu 14.04.1, then there is a problem.

    filename: main.cpp
    Code:
    #include <iostream>
    #include "add.h" // this brings in the declaration for add()
     
    int main()
    {
        using namespace std;
        cout << "\nHello, World!\n\nThe sum of 3 and 4 is " << add(3,4) << "\n" << endl;
        return 0;
    }
    filename: add.h
    Code:
    #ifndef ADD_H
    #define ADD_H
     
    int add(int x, int y); // function prototype for add.h
     
    #endif
    I try using these

    g++ -Wall -W -Werror main.cpp -I. -o CPPHelloWorld

    or just simply
    g++ main.cpp -I. -o CPPHelloWorld

    error message:
    Code:
    tmp/cccwZdcy.o: In function `main':
    main.cpp:(.text+0x1a): undefined reference to `add(int, int)'
    collect2: error: ld returned 1 exit status
    Am I missing anything?

    Thanks.

  2. #2
    Join Date
    Apr 2012
    Beans
    6,178

    Re: undefined reference in g++

    Hello and welcome to the forums

    Where is the 'add' function actually defined? Declaring something is not the same as defining it - in this case, g++ is able to compile your file (because you have declared the function prototype for 'add') but the linker is failing to link the pieces together into an executable binary file

  3. #3
    Join Date
    Aug 2014
    Beans
    14

    Re: undefined reference in g++

    Ah, you are right, I'm missing one file add.cpp

    Code:
    // #include <iostream>
    
    int add(int x,int y)
    {
        return x+y;
    }
    It's still saying undefined reference to 'add(int, int)'

  4. #4
    Join Date
    Aug 2014
    Beans
    14

    Re: undefined reference in g++

    Problem solved. I forget to include add.cpp while executing g++ command in terminals.

    Thanks for the hint, steeldriver!

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •