Undefined Reference To

C error: undefined reference to function, but it IS defined

How are you doing the compiling and linking? You'll need to specify both files, something like:

gcc testpoint.c point.c

...so that it knows to link the functions from both together. With the code as it's written right now, however, you'll then run into the opposite problem: multiple definitions of main. You'll need/want to eliminate one (undoubtedly the one in point.c).

In a larger program, you typically compile and link separately to avoid re-compiling anything that hasn't changed. You normally specify what needs to be done via a makefile, and use make to do the work. In this case you'd have something like this:

OBJS=testpoint.o point.o

testpoint.exe: $(OBJS)
gcc $(OJBS)

The first is just a macro for the names of the object files. You get it expanded with $(OBJS). The second is a rule to tell make 1) that the executable depends on the object files, and 2) telling it how to create the executable when/if it's out of date compared to an object file.

Most versions of make (including the one in MinGW I'm pretty sure) have a built-in "implicit rule" to tell them how to create an object file from a C source file. It normally looks roughly like this:

.c.o:
$(CC) -c $(CFLAGS) $<

This assumes the name of the C compiler is in a macro named CC (implicitly defined like CC=gcc) and allows you to specify any flags you care about in a macro named CFLAGS (e.g., CFLAGS=-O3 to turn on optimization) and $< is a special macro that expands to the name of the source file.

You typically store this in a file named Makefile, and to build your program, you just type make at the command line. It implicitly looks for a file named Makefile, and runs whatever rules it contains.

The good point of this is that make automatically looks at the timestamps on the files, so it will only re-compile the files that have changed since the last time you compiled them (i.e., files where the ".c" file has a more recent time-stamp than the matching ".o" file).

Also note that 1) there are lots of variations in how to use make when it comes to large projects, and 2) there are also lots of alternatives to make. I've only hit on the bare minimum of high points here.

What is an undefined reference/unresolved external symbol error and how do I fix it?

Compiling a C++ program takes place in several steps, as specified by 2.2 (credits to Keith Thompson for the reference):

The precedence among the syntax rules of translation is specified by the following phases [see footnote].

  1. Physical source file characters are mapped, in an implementation-defined manner, to the basic source character set
    (introducing new-line characters for end-of-line indicators) if
    necessary. [SNIP]
  2. Each instance of a backslash character (\) immediately followed by a new-line character is deleted, splicing physical source lines to
    form logical source lines. [SNIP]
  3. The source file is decomposed into preprocessing tokens (2.5) and sequences of white-space characters (including comments). [SNIP]
  4. Preprocessing directives are executed, macro invocations are expanded, and _Pragma unary operator expressions are executed. [SNIP]
  5. Each source character set member in a character literal or a string literal, as well as each escape sequence and universal-character-name
    in a character literal or a non-raw string literal, is converted to
    the corresponding member of the execution character set; [SNIP]
  6. Adjacent string literal tokens are concatenated.
  7. White-space characters separating tokens are no longer significant. Each preprocessing token is converted into a token. (2.7). The
    resulting tokens are syntactically and semantically analyzed and
    translated as a translation unit. [SNIP]
  8. Translated translation units and instantiation units are combined as follows: [SNIP]
  9. All external entity references are resolved. Library components are linked to satisfy external references to entities not defined in the
    current translation. All such translator output is collected into a
    program image which contains information needed for execution in its
    execution environment.
    (emphasis mine)

[footnote] Implementations must behave as if these separate phases occur, although in practice different phases might be folded together.

The specified errors occur during this last stage of compilation, most commonly referred to as linking. It basically means that you compiled a bunch of implementation files into object files or libraries and now you want to get them to work together.

Say you defined symbol a in a.cpp. Now, b.cpp declared that symbol and used it. Before linking, it simply assumes that that symbol was defined somewhere, but it doesn't yet care where. The linking phase is responsible for finding the symbol and correctly linking it to b.cpp (well, actually to the object or library that uses it).

If you're using Microsoft Visual Studio, you'll see that projects generate .lib files. These contain a table of exported symbols, and a table of imported symbols. The imported symbols are resolved against the libraries you link against, and the exported symbols are provided for the libraries that use that .lib (if any).

Similar mechanisms exist for other compilers/ platforms.

Common error messages are error LNK2001, error LNK1120, error LNK2019 for Microsoft Visual Studio and undefined reference to symbolName for GCC.

The code:

struct X
{
virtual void foo();
};
struct Y : X
{
void foo() {}
};
struct A
{
virtual ~A() = 0;
};
struct B: A
{
virtual ~B(){}
};
extern int x;
void foo();
int main()
{
x = 0;
foo();
Y y;
B b;
}

will generate the following errors with GCC:

/home/AbiSfw/ccvvuHoX.o: In function `main':
prog.cpp:(.text+0x10): undefined reference to `x'
prog.cpp:(.text+0x19): undefined reference to `foo()'
prog.cpp:(.text+0x2d): undefined reference to `A::~A()'
/home/AbiSfw/ccvvuHoX.o: In function `B::~B()':
prog.cpp:(.text._ZN1BD1Ev[B::~B()]+0xb): undefined reference to `A::~A()'
/home/AbiSfw/ccvvuHoX.o: In function `B::~B()':
prog.cpp:(.text._ZN1BD0Ev[B::~B()]+0x12): undefined reference to `A::~A()'
/home/AbiSfw/ccvvuHoX.o:(.rodata._ZTI1Y[typeinfo for Y]+0x8): undefined reference to `typeinfo for X'
/home/AbiSfw/ccvvuHoX.o:(.rodata._ZTI1B[typeinfo for B]+0x8): undefined reference to `typeinfo for A'
collect2: ld returned 1 exit status

and similar errors with Microsoft Visual Studio:

1>test2.obj : error LNK2001: unresolved external symbol "void __cdecl foo(void)" (?foo@@YAXXZ)
1>test2.obj : error LNK2001: unresolved external symbol "int x" (?x@@3HA)
1>test2.obj : error LNK2001: unresolved external symbol "public: virtual __thiscall A::~A(void)" (??1A@@UAE@XZ)
1>test2.obj : error LNK2001: unresolved external symbol "public: virtual void __thiscall X::foo(void)" (?foo@X@@UAEXXZ)
1>...\test2.exe : fatal error LNK1120: 4 unresolved externals

Common causes include:

  • Failure to link against appropriate libraries/object files or compile implementation files
  • Declared and undefined variable or function.
  • Common issues with class-type members
  • Template implementations not visible.
  • Symbols were defined in a C program and used in C++ code.
  • Incorrectly importing/exporting methods/classes across modules/dll. (MSVS specific)
  • Circular library dependency
  • undefined reference to `WinMain@16'
  • Interdependent library order
  • Multiple source files of the same name
  • Mistyping or not including the .lib extension when using the #pragma (Microsoft Visual Studio)
  • Problems with template friends
  • Inconsistent UNICODE definitions
  • Missing "extern" in const variable declarations/definitions (C++ only)
  • Visual Studio Code not configured for a multiple file project

What causes the error undefined reference to (some function)?

It's a linker error. ld is the linker, so if you get an error message ending with "ld returned 1 exit status", that tells you that it's a linker error.

The error message tells you that none of the object files you're linking against contains a definition for avergecolumns. The reason for that is that the function you've defined is called averagecolumns (in other words: you misspelled the function name when calling the function (and presumably in the header file as well - otherwise you'd have gotten a different error at compile time)).

C++ error 'Undefined reference to Class::Function()'

What are you using to compile this? If there's an undefined reference error, usually it's because the .o file (which gets created from the .cpp file) doesn't exist and your compiler/build system is not able to link it.

Also, in your card.cpp, the function should be Card::Card() instead of void Card. The Card:: is scoping; it means that your Card() function is a member of the Card class (which it obviously is, since it's the constructor for that class). Without this, void Card is just a free function. Similarly,

void Card(Card::Rank rank, Card::Suit suit)

should be

Card::Card(Card::Rank rank, Card::Suit suit)

Also, in deck.cpp, you are saying #include "Deck.h" even though you referred to it as deck.h. The includes are case sensitive.

Undefined Reference to (FUNCTIONNAME) in C

Try:

gcc -c SGGINPUT.h SGGINPUT.c

A result file will be an obj file:

SGGINPUT.o

Next compile it this way:

gcc -g SGGINPUT.o test.c -o "Output_name"

Plus you don't really need to include <stdio.h> in your header, you are just declaring your functions there and nothing more.

Undefined reference to object when compiling with a header file

It's because you are not including Person.cpp as a compiling parameter. You need to add Person.cpp aswell as main.cpp file

How to solve undefined reference in main function?

After you comment, even if including the cpp files is a workaround, please do not do that!

You have two acceptable ways.

  1. define the method in the class itself in the include file

    Some IDE by default create an include file containing only the method declarations and put the definitions in an implementation cpp file. But the standard allow the definition to be inside the class definition, it is commonly used for small methods or templates (*)

    So your header could be:

     #ifndef PID_H
    #define PID_H
    class PID
    {
    float _kp,_ki,_kd,_error,_previous_error,_dt;
    public:
    void set_params(float kp, float ki, float kd,float error,float previous_error,float dt) {
    _kp = kp;
    _ki = ki;
    _kd = kd;
    _error = error;
    _previous_error = previous_error;
    _dt = dt;
    }

    };

    #endif
  2. add the pid.cpp file to the list of source files for your project.

    This part actually depends on your build tools. But your screenshot shows that you already compile app.cpp and main.cpp. You just have to process pid.cpp the same way.


For templates, the recommended way is to put all the implementation in the include file. Not doing so requires to consistently explicitely instanciate the template for all its future usages, which is not an option in a general library.

Why does the compiler is giving me this: undefined reference to function?

You can fix this by doing three things:

  1. Don't include a .c file. You're already providing it to gcc on the command line.
  2. Include help.h in files where you use those functions.
  3. Not using inline. You can't use inline when the caller and callee are in different translation units.

main.c:

#include <stdio.h>
// #include "funcs.c"
#include "help.h"

int main()
{
int z = 0;
int wh = 1;
while (wh == 1)
{
printf("What you want?\n1-Plus\n2-Minus\n");
scanf("%d", &z);
if (z == 1)
{
plus();
}
if (z == 2)
{
minus();
}
}
printf("The program ended\n");

return 0;
}

funcs.c

#include <stdio.h>

void plus(void)
{
int a = 0;
int b = 0;
printf("Pls insert a numb\n");
scanf("%d", &a);
printf("Pls insert a numb\n");
scanf("%d", &b);
a = a + b;
printf("The result is: %d\n", a);
}

void minus(void)
{
int a = 0;
int b = 0;
printf("Pls insert a numb\n");
scanf("%d", &a);
printf("Pls insert a numb\n");
scanf("%d", &b);
a = a - b;
printf("The result is: %d\n", a);
}

help.h:

extern int a;
extern int b;
extern int z;
extern int wh;
void minus(void);
void plus(void);

Compile and run like so:

$ gcc -Wall -Werror funcs.c main.c
$ ./a.out
What you want?
1-Plus
2-Minus
^C

Other thoughts:

extern int a;
extern int b;
extern int z;
extern int wh;

You're already declaring these variables locally. This is unneeded. The extern keyword tells the compiler that these variables are defined in another translation unit that it can't see. This isn't true, so you should just remove these.

C++: Undefined Reference to 'CYourClass::Method()'

It looks as though you are doing something like:

g++ dog.cpp -o dog

Without the -c flag (for compile only, don't link) the compiler will attempt to make an executable from that one file.

Generally speaking you need to do one of the following:

  1. Compile each cpp file separately, and then link at the end
# compilation
g++ -c dog.cpp -o dog.o
g++ -c breeds.cpp -o breeds.o
g++ -c main.cpp -o main.o

# now link the 3 object files into the exe
g++ -o myApp main.o dog.o breeds.o
  1. Compile them in one go
g++ -o myApp main.cpp dog.cpp breeds.cpp

  1. Use a makefile
all : myApp

# dog.o depends on dog.cpp & breeds.h. When those change, run line below
dog.o: dog.cpp breeds.h
gcc -c -o dog.o dog.cpp

breeds.o: breeds.cpp dog.h
gcc -c -o breeds.o breeds.cpp

main.o: main.cpp breeds.h dog.h
gcc -c -o main.o dog.cpp

# final app depends on the object files, when they change, recompile.
myApp: main.o dog.o breeds.o
gcc -o myApp main.o dog.o breeds.o

clean:
rm -f *.o

  1. Use some IDE to manage this for you (or use something like cmake)


Related Topics



Leave a reply



Submit