Ошибка undefined reference to main

You should be able to compile list.cpp, you can’t link it unless you have a main program. (That might be a slight oversimplification.)

The way to compile a source file without linking it depends on what compiler you’re using. If you’re using g++, the command would be:

g++ -c list.cpp

That will generate an object file containing the machine code for your class. Depending on your compiler and OS, it might be called list.o or list.obj.

If you instead try:

g++ list.cpp

it will assume that you’ve defined a main function and try to generate an executable, resulting in the error you’ve seen (because you haven’t defined a main function).

At some point, of course, you’ll need a program that uses your class. To do that, you’ll need another .cpp source file that has a #include "list.h" and a main() function. You can compile that source file and link the resulting object together with the object generated from list.cpp to generate a working executable. With g++, you can do that in one step, for example:

g++ list.cpp main.cpp -o main

You have to have a main function somewhere. It doesn’t necessarily have to be in list.cpp. And as a matter of style and code organization, it probably shouldn’t be in list.cpp; you might want to be able to use that class from more than one main program.

As a beginner c++ developer , you probably might get error like undefined reference to `main’.

Generally this error occurs when we forgot not define main() function in program. In any c++ program main() function is necessary to start a program. So whenever you create any class then do not forgot to add main function in your project and then you can call class functions from main.

#include <iostream>
using namespace std;

class A{
public:
    int GetValue();
};

int A::GetValue()
{
    return 0;
}

Output:

 undefined reference to `main' c++

Here we have just created class inside our program and not define any main function. So here we are getting error undefined reference to main c++.

SOLUTION : Undefined reference to main c++

We can resolve this error by adding main function inside program.

#include <iostream>
using namespace std;

class A{
public:
    int GetValue();
};

int A::GetValue()
{
    return 0;
}

int main()
{
    return 0;
}

Also many time possible for new developer of someone coming from C# background that they define main() function inside class. So just remember that we have to define main() function as a global in C++.

// Declare global inside file
int main()
{
    return 0;
}

undefined reference to func() c++

When we declare and function but not added it’s definition then we get undefined reference to func c++ error.

#include <iostream>
using namespace std;

void func();
int main()
{
    func();
    return 0;
}

Here we will get error by compiler :

Compilation failed due to following error(s). main.cpp:(.text+0x5): undefined reference to `func()’

SOLUTION : Undefined reference to function c++

We can resolve it by adding c++ function definition.

#include <iostream>
using namespace std;

void func();
int main()
{
    func();
    return 0;
}

void func()
{
    cout<<"Hello";
}

CONCLUSION:

Make sure in c++ whenever you are getting any compilation errors like undefined reference to main c++ or undefined reference to func c++ ( here func can be any name of function.) then you have to add definition of that function inside your file. Once you have added definition of function then you will not get any undefined reference c++ error and program will be executed successfully.

Reader Interactions

Home »
C programs »
C common errors programs

Here, we will learn why an error: undefined reference to ‘main’ occurs and how to fix it in C programming language?

Submitted by IncludeHelp, on September 04, 2018

The error: undefined reference to ‘main’ in C program is a very stupid mistake by the programmer, it occurs when the main() function does not exist in the program. If you used main() function and still the error is there, you must check the spelling of the main() function.

Consider the given example, here I wrote mian() instead of main(), see the spelling of main() which is not correct in the program.

Example:

#include <stdio.h>

int mian(void) {
	printf("Hello world!");
	return 0;
}

Output

/usr/lib/gcc/x86_64-linux-gnu/6/../../../x86_64-linux-gnu/Scrt1.o: In function '_start':
(.text+0x20): undefined reference to 'main'
collect2: error: ld returned 1 exit status

How to fix?

To fix this error, correct the spelling of the main() function.

Correct code:

#include <stdio.h>

int main(void) {
	printf("Hello world!");
	return 0;
}

Output

Hello world!

C Common Errors Programs »


Undefined reference to main is an error message that indicates that the linker is unable to find a definition for the “main” function during the process of compiling your C or C++ program. This article will explain five factors that can prevent the linker from finding the “main” function in your code and how you can correct the error.Undefined Reference to Main in C Code

From this, you’ll know more about the importance of the “main” function in your program and why the linker wants it before you can compile your code. To get started, open your project that’s showing the error message, and let’s explain how you can fix it.

Contents

  • Why Is There no Reference to “Main”? Discussing All Causes
    • – There Is No “Main” Function in Your Code
    • – You Did Not Save Your File
    • – You Misspelled the “Main” Function
    • – You Did Not Add “target_link_libraries()” in Ros
    • – You Have a Corrupted Core Compilation Cache File
  • How To Ensure a Reference to Main in Your Code?
    • – Check the “Main” Function in Your Code
    • – Save Your File Before Compilation
    • – Check Your Code for Typographical Errors
    • – Add the “target_link_libraries()” Command to “Cmakelists”
    • – Remove the Corrupted Compilation Cache File
  • Conclusion

Why Is There no Reference to “Main”? Discussing All Causes

There is no reference to “main” because of the following:

  • There is no “main” function in your code
  • You did not save your file
  • You misspelt the “main” function
  • You did not add “target_link_libraries()” in ROS
  • You have a corrupted core compilation cache file

– There Is No “Main” Function in Your Code

The cause of the “undefined reference to main C” error message is that there is no “main” function in your code, or somehow the linker cannot find it. That’s because for a C or C++ program to compile successfully, it should have the “main” function that will serve as the entry point of the application.

For example, there is no “main” function in the following program, and when you run the code using GCC, you’ll get a compiler error message. Part of the latter will be “in function _start’ undefined reference to main’” or, in its full form, it can be “in function _start’: (.text+0x20): undefined reference to `main’“.

#include <stdio.h>

void print_message() {

printf(“Hello, world!n”);

}

– You Did Not Save Your File

Not saving your file can lead to an “undefined reference to main” error, and this gets confusing if you already have the “main” function and your compiler is telling you that it cannot find it. And this is true because you’re trying to compile an empty source file without saving your file.

Most compilers will not allow this, and the reason is as follows: the source file in your code editor is still in memory, and you’ve not written it to disk. So, without doing the latter, the compiler will see only an empty C or C++ source file and will throw the error during compilation.

– You Misspelled the “Main” Function

If you misspell the “main” function as “mainn” or another spelling that’s not “main”, the compiler or linker will not be able to find the correct entry point for your program.Ensure a Reference to Main in C Code

This also means that “main” is case-sensitive so if you write “Main” or “MAIN” instead of “main”, the compiler will not recognize it as a valid entry point.

The following is an example and when you compile the code, you’ll get an error:

#include <stdio.h>

// Incorrect declaration of “main” function

int MAIN() {

printf(“Hello, world!n”);

return 0;

}

/* The following are also wrong:

int maIn() {

printf(“Hello, world!n”);

return 0;

}

int Main() {

printf(“Hello, world!n”);

return 0;

}*/

– You Did Not Add “target_link_libraries()” in Ros

In ROS (Robot Operating System), if you are compiling a package that includes a node, you need to link the necessary ROS libraries using the “target_link_libraries()” function.

Normally, you’ll do this in your “CMakeLists.txt” file, and if you forget to include it, you can encounter the “undefined reference to `main’ ROS” error when you try to compile your package.

The reason for this error is that ROS nodes are essentially C++ programs that require a main function. When you forget to link the necessary ROS libraries, the linker will not be able to find the definition for the main function that it needs to execute your node.

– You Have a Corrupted Core Compilation Cache File

One possible cause of the “undefined reference to main Arduino” error in Arduino is a corrupted core compilation cache file. This can happen after you update your Arduino IDE or when there are issues with the installation.

Behind the scenes, the core compilation cache file is responsible for caching the compiled code of the Arduino core library. And when it becomes corrupted, it can cause issues with the compilation process.

How To Ensure a Reference to Main in Your Code?

To ensure a reference to “main” in your code, use any of the following methods:

  • Check the “main” function in your code
  • Save your file before compilation
  • Check your code for typographical errors
  • Add the “target_link_libraries()” command to “CMakeLists”
  • Remove the corrupted compilation cache file

– Check the “Main” Function in Your Code

To solve the “undefined reference to main’ gcc” error, check the “main” function in your code and if it’s not there, you should add it. For example, the following example did not work because there is no “main” function:

#include <stdio.h>

void print_message() {

printf(“Hello, world!n”);

}

If you change it to the following, the compiler will compile the code and output “Hello, world!”. This works because we added a “main” function that will serve as the entry point of the program.

#include <stdio.h>

void print_message();

int main() {

print_message();

return 0;

}

void print_message() {

printf(“Hello, world!n”);

}

The addition of the “main” function to your code also works if you’re using a makefile, and you’re seeing the “undefined reference to main makefile‘ error.

Finally, if you’re trying to create an executable from multiple source files, you can see the “undefined reference to `main’ cmake” error. To solve this, specify all the required source files in the “add_executable()” command like “add_executable(my_program main.cpp another_source_file.cpp yet_another_source_file.cpp)”. And ensure that the “main” function is defined in one of the source files and is reachable through the code.

– Save Your File Before Compilation

Saving your file before compilation is an important step to ensure that the compiler finds the “main” function in your code. So, after typing your code, always save it with “Ctrl + S” on your keyboard or using the GUI menu of your editor.No Reference to Main Causes

You can also configure your text editor or Integrated Development Environment (IDE) to automatically save your changes when you build your project.

For this, select any of the following options that apply to you:

  • Visual Studio Code: Go to File > Auto Save or use the keyboard shortcut Ctrl + Shift + P to open the Command Palette and search for “auto-save” to find the relevant options.
  • Sublime Text: Go to Preferences > Settings and add the following line to your user settings file: “save_on_build”: true
  • Atom: Go to File > Settings > Packages > build > Settings and enable the “Save On Build” option.
  • Eclipse: Go to Window > Preferences > Run/Debug > Launching and check the “Always save resources before launching” option.

– Check Your Code for Typographical Errors

Checking your code for typographical errors, especially the spelling of “main” can prevent the undefined reference error. The first thing that you should remember is that “main” is case-sensitive, and always write it as shown in the following code example:

#include <stdio.h>

// Correct declaration of “main” function

int main() {

printf(“Hello, world!n”);

return 0;

}

– Add the “target_link_libraries()” Command to “Cmakelists”

Adding the “target_link_libraries()” command to “CmakeLists.txt” in ROS will solve the “undefined reference to main” error. For example, in the following, we use the “target_link_libraries()” function to link the necessary ROS libraries (specified by ${catkin_LIBRARIES}) to the “my_node” executable.

By doing this, the linker will be able to find the definition for the main function and successfully compile your ROS node.

cmake_minimum_required(VERSION 2.8.3)

project(my_node)

## Find catkin and any catkin packages

find_package(catkin REQUIRED COMPONENTS roscpp std_msgs)

## Declare a catkin package

catkin_package()

## Build the node

include_directories(include ${catkin_INCLUDE_DIRS})

add_executable(my_node src/my_node.cpp

## Link the necessary ROS libraries

target_link_libraries(my_node ${catkin_LIBRARIES})

– Remove the Corrupted Compilation Cache File

To fix the “undefined reference to main” error while working with Arduino, you can try deleting the cache file and restarting the Arduino IDE. The location of the cache file may vary depending on the operating system and the version of the Arduino IDE.

But it is typically located in the following directory:

  • On Windows: C:Users%USERNAME%AppDataLocalArduino15cache
  • On macOS: /Users/%USERNAME%/Library/Arduino15/cache
  • On Linux: ~/.arduino15/cache

But, if you see the error after selecting Arduino Uno, you should delete the core cache file or all the Arduino files in the following location:

C:Users<your_user_name>AppDataLocalTemparduino-core-cache

Conclusion

This article explained five factors that will cause the “undefined reference to main” error in your code and how you can prevent it. Using the following summary, you’ll reduce the possibility of the error in your code and projects:

  • Where your code has no reference to “main”, your compiler will throw an “undefined reference” error.
  • Not saving your file and misspelling the “main” function can prevent the linker from finding the “main” function in your code.
  • You can solve an “undefined reference” to the main error by including the “main” function in your code and ensuring that you save your code before compiling it.
  • In Arduino, you can delete the corrupted compilation cache file if you’re seeing the “undefined reference” to “main” error.

With everything that you’ve learned about the “main” function, you can ensure that your compiler finds it without throwing an undefined reference error. Finally, we’re glad that you have read this far, it means a lot to us, and don’t forget to share our article!

  • Author
  • Recent Posts

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

  1. Types of Errors in C++
  2. Fix the Undefined Reference to main() Error in C++

Fix the Undefined Reference to Main Error in C++

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

  1. Types of Errors in C++
  2. Fix the Undefined Reference to main() Error in C++

Fix the Undefined Reference to Main Error in C++

This quick tutorial will briefly discuss one of the most common and equally critical errors in C++ programming, i.e., Undefined Reference to main().

First, we will briefly discuss different errors that can occur while coding in C++. Then, we will explain the causes and fixes for the Undefined Reference error.

Types of Errors in C++

Like any other programming language, the C++ codes may be subjected to errors or bugs for multiple reasons. These errors are broadly classified into the following error categories:

  • Syntax Errors
  • Run-time Errors
  • Logical Error
  • Linker Error

Syntax Errors are the errors that occur due to violations in the rules of C++ or any syntaxes. Run-time Errors occur when there is no issue in the program syntactically but is detected at the time of execution and lead to a program crash.

Logical Errors occur when we are not getting our desired results or output, which means there is some mistake in the logic of our program. Linker Errors are errors when the program is compiled successfully and tries to link some other objects with our main object file; thus, the executable is not generated.

Examples are any wrong prototype of the function defined, any incorrect header file included, etc.

Fix the Undefined Reference to main() Error in C++

This error is most frequently occurring in C++ and is equally critical, especially for new programmers. This type of linker error can affect the running of the program.

These errors mainly occur when the program is compiled successfully and is at the linking phase trying to link other object files with the main object.

The Undefined Reference error occurs when we have not included the main() function in our code. Usually, with multi-file projects, programmers often forget to include the main() function.

The main() function is the driver function and serves as the entry point for every program. Therefore, if the main() function definition is missing, the program generates the error Undefined Reference to main().

The syntax for this function is as follows:

int main()
{
    //some code here
    return 0;
}

Понравилась статья? Поделить с друзьями:
  • Ошибка uncaught referenceerror jquery is not defined
  • Ошибка undefined method for nil nilclass nomethoderror
  • Ошибка unb на стиральной машине haier что это такое
  • Ошибка undefined is not an object evaluating
  • Ошибка unb на стиральной машине haier как исправить ошибку