`undefined reference to `main` in Cpp class without main() - c++

I came across this while trying to get an answer. But it seems like the poster had multiple files and they were not getting linked, and hence the error.
But, why do I get this error when using a single file?
g++ myClass.cpp
/usr/lib/gcc/i686-redhat-linux/4.6.3/../../../crt1.o: In function `_start':
(.text+0x18): undefined reference to `main'
collect2: ld returned 1 exit status
And why is main necessary here at compile time (from where does it find a mention of main in my code) ? main is the starting point of code execution, but why does the compiler assume i need a main here. I can have it defined in some other file and use gcc -o to make an executable?
Or maybe I am missing something else in the code which causes the error?
#include<iostream>
class myClass
{
public:
myClass()
{
std::cout<<"Constructor";
}
~myClass()
{
std::cout<<"Destructor";
}
};

main is not necessary to compile a source file. It is necessary to link a program into an executable [1], because the program has to start somewhere.
You need to tell the compiler that "this is not the whole of my program, just compile, but don't link", using the '-c' option, so
g++ -c myClass.cpp
which will produce a myClass.o file that you can then use later, e.g.
g++ -o myprog myClass.o myOtherClass.o something_that_has_main.o -lsomelib
(Obviously, substitute names with whatever you have in your project)
[1] Assuming you use the regular linker scrips that come with the compiler. There are "ways around that too", but I think that's beyond this answer.

You are trying to compile an executable, so a main function is expected. You should compile an object file by using the -c flag:
g++ -c myClass.cpp
While you are at it, I suggest adding warning flags -Wall -Wextra at the very least.

You are building your source as an application. Add -c option to produce only object file:
g++ -c myClass.cpp

Compile only?! use -c option
g++ -c file.cpp
otherwise the project needs a main.

You need to use the -c flag to compile and only tell the compiler to generate an object file. You're telling the compiler to make an executable.

Related

Why am I getting "undefined reference to main"

I am a very new to programming and have a very basic question that may be answered in other threads however I think they are far too advanced for me to understand how. I have actually found many answers so far on this site but this is the first problem that forced me to create an account and ask.
Anyway i am running a very basic example program on linux mint 18.3. Now I have seen this exact code work on a machine with windows 8 I believe so I was wondering if that could be the problem. I have created a class and when i plug in my object then build and run I get:
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o||In function _start':|
(.text+0x20)||undefined reference tomain'|
This is the entire code:
#include <iostream>
#include "Gladius.h"
using namespace std;
int main()
{
Gladius io;
return 0;
}
Thats it very basic. here is the .h
#ifndef GLADIUS_H
#define GLADIUS_H
class Gladius
{
public:
Gladius();
};
#endif // GLADIUS_H
and the .cpp for the class.
#include "Gladius.h"
#include <iostream>
using namespace std;
Gladius::Gladius()
{
cout << "The Gladius is a short sword" << endl;
}
I know this seems extremely simple but I am just learning to code and i have been looking all over for an explanation why this isn't working yet I see it work on another pc exactly as is. Anyway any explanation would be greatly appreciated.
Here is what i found in command line If this answers your questions about what was in the cmd.
g++ -Wall -fexceptions -g -std=c++11 -Wall -I -c /home/gator/Documents/Spartan1/Gladius.cpp -o obj/Debug/Gladius.o
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o: In function _start':
(.text+0x20): undefined reference tomain'
collect2: error: ld returned 1 exit status
Know the compiler options(gcc/g++ compiler):
-c : Compile and assemble, but do not link
-o file : Place the output into file
So when you run
g++ filename.cpp -o executable_name
, you generate an application which can be executed.
The problem is you are compiling, assembling as well as linking when you are trying to compile "Gladius.cpp" and compiler is trying to search for main() definition.
So in your case, the compilation steps would be:
First compile "Gladius.cpp" and generate object file "Gladius.o":
g++ -Wall -fexceptions -g -std=c++11 -c Gladius.cpp
Next compile "main.cpp" and generate object file "main.o":
g++ -Wall -fexceptions -g -std=c++11 -c main.cpp
Generate executable by linking "main.o" and "Gladius.o"
g++ -Wall -fexceptions -g -std=c++11 -o main main.o Gladius.o
Now you can run "main":
./main
Your compiler's command line contains -I -c sequence.
This -I option "swallows" your -c option. -I requires an additional argument, which is an include directory name. You failed to supply that argument, which is why -I assumes that -c that follows it is the directory name. So that -I consumes that -c.
The compiler never sees that -c. Without -c it assumes that you want to compile and link your program. Since Gladius.cpp does not have main in it, you get the error at linking stage.
Here 's a simple demo of the same problem: http://coliru.stacked-crooked.com/a/8a37cd3e90a443e2
You need to figure out why you have an orphaned -I in your command line.
If you are compiling this code using a command line like:
g++ -Wall -Wextra -Werror -O gladius.cpp -o output.exe
then make sure that you include all the .cpp files (not .h files) that contain code that your program needs.
g++ -Wall -Wextra -Werror -O gladius.cpp main.cpp -o output.exe
I explain this to beginners all the time as each .cpp being a bag of Lego's in a kit. You need all the bags that came with the box in order to build the kit. If you omitted main.cpp (or the file that contains main) then you will get the linker error that you are currently getting.
What command are you using to compile, link, and then execute? It should look something like
$ g++ main.cpp gladius.cpp -odemo
$ ./demo
check your command line for linking step.. You may forgot file with main as input, or you had forgot output file name after -o (and masked main.o in result)
I had this very kind of problem myself, and though it may not be the conventional, "proper" solution, I simply renamed the ".c" file to ".cpp", and it all worked.
After all, I was compiling both c and c++ together with a c++ compiler (recommended by the library), and the c code already had the proper c++ #extern flags (see here for more on that).
Also related:
C++ Error: undefined reference to `main'
Including C Code in C++
Why do you need an explicit `-lm` compiler option
Compilation on Linux - In function '_start': (.text+0x20): undefined reference to 'main'

Trouble making a header file

I am trying to make my own header file which will contain a class Vector.
To create a header file, as advised by some websites, I have created two different files :-
1) collections.h (contains declarations)
2) collections.cpp (contains definition)
Another file is main.cpp, which contains the main function, and in which I will be using collections.h
All these files are in the same directory
The trouble I am having is that compiler is showing the error
Undefined reference to Vector::Vector(int, int)
and so on for all the functions in my class.
I have made sure that there is a #include "collections.h" line in both collections.cpp as well as main.cpp
How can I solve the above problem?
I am using gcc compiler under ubuntu 12.04
First build the object files:
gcc -c main.cpp -o main.o
gcc -c collections.cpp -o collections.o
then link them together:
gcc collections.o main.o -o main
You need to build both source files and link them together.
On a Linux command line, you can do it simplest by providing both source files to gcc:
$ g++ -Wall main.cpp collections.cpp -o my_program
Note: I added the -Wall option to enable more warnings by default. It's always a very good habit to enable more warnings, as they can often point out logical errors or possible places where you have undefined behavior.

Linker error in switching from cc compiler to g++ compiler

I have been using C to code for sometime and I had no issues in compiling and linking my code to archive libraries (.a files). However, now I need to switch to C++ and doing so, I have to use g++ instead of cc for linking and compiling.
Using C, first thing to do was compiling the source and creating the object file and then linking it to the library using the same command but without the -c option:
cc -c -ggdb -Wall -Werror -I.. test.c -o test.o
cc -o test -ggdb -Wall -Werror test.o ../libpmem/libpmem.a
As I think the same procedure should be done for doing the same thing with g++, I tried to change the compiling and linking phase as follow:
g++ -c -ggdb -Wall -Werror -I.. test.c -o test.o
g++ test.o -I.. -L/path/libpmem -lpmem -o test
Although both sets should do the same thing, I always get an error while trying to link using g++. Here is the error message:
test.o: In function `main':
/path/test/test.c:5: undefined reference to `pmem_msync_mode()'
collect2: ld returned 1 exit status
make: *** [all] Error 1
There must be something wrong with the linking phase as the method definition must be found in the library file (just as the cc linker can find the definition and do the linking without any problem).
I also tried to do both linking and compiling using a single g++ command, but no matter what I do, I always get the same error. Any idea how can I fix this?
you probably have some sort of name mangling problem...
since it looks like that is declared in a c library there should already be some sort of
#ifdef __cplusplus
extern "C" {
#endif
int pmem_msync_mode();
#ifdef __cplusplus
}
#endif
but if there isn't in the library header you may have to do something like;
extern "C" {
#include <pmem.h>
}
See http://www.cplusplus.com/forum/general/1143/
You need to tell the compiler that the code is compiled as C
I am assuming that the pmem library is compiled and linked as C code.
C and C++ have different conventions for how they store the names of functions in binary format. See http://en.wikipedia.org/wiki/Name_mangling for a reference.
To solve your problem, probably the solution is to:
extern "C" {
#include <pmem.h>
}
When the C++ compiler imports the function declarations from the header, without external C linkage being specified, it expects the binary it links against to have the associated functions' representations in a different format, namely whatever format your C++ compiler mangles function names to.

C++ multi-stage linking

Ok, so this might not be a great question, but I'm a bit stuck.
I have 3 programs:
pegio.c/pegio.h - Does hardware initialization and functions for my device
PegIOHandler.cpp/PegIOHandler.h - Handles I/O for device
PegRTU.cpp - Main function
My project implements the opendnp3 (which allows one to transmit data using the DNP3 protocol) library.
Now, to compile it I first compile the pegio.c file
gcc -c pegio.c -o pegio.o
Easy, up to here I understand.
Secondly I compile the IOHandler and reference pegio.c as it uses it.
g++ -c PegIOHandler.cpp pegio.c -o PegIOHandler.o -std=c++0x
Now it gives me the following output.
g++: warning: pegio.o: linker input file unused because linking not done
But, it still creates the object file. HOWEVER, PegIOHandler implements opendnp3 header files, which is included in PegIOHandler.cpp and PegIOHandler.h. When I attempt to compile these files without using the '-c', it tells me that there are undefined references to the opendnp3 files. I know I have to link them to my project, but how do I do that?
Then compililing my third and final file:
g++ PegRTU.cpp pegio.o PegIOHandler.o -o pegrtu -std=c++0x
This now tells me that there are undefined references to the opendnp3 files.
So: How do I link the opendnp3 library to my project / code files???
Thanks!
Ouch. So many misunderstandings. You don't need the previously compiled object files to compile further source files to object code. However, you do need to link them together at the end of the compilation process, including any libraries required. All in all:
gcc -c pegio.c -o pegio.o
g++ -c PegIOHandler.cpp -o PegIOHandler.o -std=c++0x
g++ -c PegRTU.cpp -o PegRTU.o -std=c++0x
g++ -o executable_name *.o -lopendnp3 # or whatever linker flag is needed for OpenDNP3
And pretty please, read this.

Linking files in g++

Recently I have tried to compile a program in g++ (on Ubuntu). Usually i use Dev-C++ (on Windows) and it works fine there as long as I make a project and put all the necessary files in there.
The error that occurs when compiling the program is:
$filename.cpp: undefined reference to '[Class]::[Class Member Function]'
The files used are as following:
The source code (.cpp) file with the main function.
The header file with the function prototypes.
The .cpp file with the definitions for each function.
Any help will be appreciated.
You probably tried to either compile and link instead of just compiling source files or somehow forgot something.
Variation one (everything in one line; recompiles everything all the time):
g++ -o myexecutable first.cpp second.cpp third.cpp [other dependencies, e.g. -Lboost, -LGL, -LSDL, etc.]
Variation two (step by step; if no -o is provided, gcc will reuse the input file name and just change the extension when not linking; this variation is best used for makefiles; allows you to skip unchanged parts):
g++ -c first.cpp
g++ -c second.cpp
g++ -c third.cpp
g++ -o myexecutable first.o second.o third.o [other dependencies]
Variation three (some placeholders):
Won't list it but the parameters mentioned above might as well take placeholders, e.g. g++ -c *.cpp will compile all cpp files in current directory to o(bject) files of the same name.
Overall you shouldn't worry too much about it unless you really have to work without any IDE. If you're not that proficient with the command line syntax, stick to IDEs first.
The command line of gcc should look like:
g++ -o myprogram class1.cpp class2.cpp class3.cpp main.cpp
Check in which cpp file the missing class member function is defined. You may have not given it to gcc.
You can also check for correct #include tags within filename.cpp. Assume that filename.cpp uses code contained in myclass.h present in the same directory as filename.cpp. Assume that the class that g++ says is undefined is contained in myclass.h and defined in myclass.cpp. So, to correctly include myclass.h within filename.cpp, do the following:
In filename.cpp:
#include <iostream>
#include <myclass.h>
//..source code.
In the makefile:
filename.o: myclass.C myclass.h filename.cpp
g++ -I./ -c filename.cpp -o filename.o
myclass.o: myclass.C myclass.h
g++ -c myclass.C -o myclass.o
In the above, note the use of -I. option when compiling filename.cpp. The -I<directory> asks g++ to include the path following the -I part into the search path. That way myclass.h is correctly included.
In the absence of more information (the source maybe), it is difficult to say with any accuracy where the problem lies. All attempts will be but stabs in the dark.
I assume that you have declared a member function (usually in a .h or .hpp file) but have ommited the respective definition of the member function (usually in a .cpp file).
In c++, it is possible to declare a class like so:
class foo {
void x();
void y();
}
with a cpp file that goes like so
void foo::x() {
do_something()
}
Note, there is no foo::y().
This poses no problem to the compiling/linking process as long as the member function foo::y() is referenced nowhere throughout the compiled code.