I am learning C++ and I got this error:
Undefined symbols:
"_main", referenced from:
start in crt1.10.6.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
my code is this
#include <stdlib.h>
#include <iostream>
class Fraction {
private:
int num, den;
public:
void set(int n, int d) {num=n; den=d; normalize();}
int get_num(){return num;}
int get_den(){return den;}
private:
void normalize();
int gcf(int a, int b);
int lcm(int a, int b);
};
void Fraction::normalize() {
if (den == 0 || num == 0) {
num = 0;
den = 1;
}
if (den < 0) {
num *= -1;
den *+ -1;
}
int n = gcf(num, den);
num = num / n;
den = den / n;
}
int Fraction::gcf(int a, int b) {
if (a % b == 0)
return abs(b);
else return gcf(b, a % b);
}
int Fraction::lcm(int a, int b) {
return(a / gcf(a, b)) * b;
}
If it helps at all, I am using GCC with the command g++ -o.
Any help much appreciated!
Where is your main function? Every "ordinary" program in C++ starts from main function, which is why the linker is looking for one. You haven't provided it. Hence the error.
I think the problem is that you're compiling a source file that doesn't contain a main function. Not every source file has to have main defined, but every C++ program needs to have it somewhere, and since you didn't post any other source files I'll assume that this is your only file. If you try compiling and linking this code, you'll get an error because there is no entry point into the program.
To fix this, either link your code together with a file that contains a main function, or add a main function to your code, or compile the code without linking it (this depends on your compiler).
Also, you should probably split your code into a .h/.cpp pair. Typically speaking, classes are defined in header files so that they can be used by other parts of the program, while implementations are left int the .cpp file so that they aren't visible to clients.
Add a -c flag when using gcc; it stops the compiler looking for the main function
Almost every C++ function has a main function, which tells the computer which part of your code it should do first. Otherwise, if someone starts your program, where should it begin? It has a form like below:
int main(int argc, char **argv) {
//what should happen when someone runs the program?
//that goes here
return 0; //program all done
}
I think u must change the extension of the file u are using to ".h" instead of ".cpp"
for example :
if this file is named as abc.cpp and u r compiling it the way "gcc abc.cpp" then u must change it to "gcc abc.h" ......
this will instruct the compiler to compile a Header rather than an object file.... :)
Related
How to solve it with two cpp files?
how to print x times "Hello world" by asking with an external function call, which is written in another c++ file?
function.cpp
#include <stdio.h>
int intf(void) {
int l;
printf("How many lines to print?");
scanf("%d", &l);
printf("%d lines to print.\n", l);
int i = 0;
while (i<l) {
printf("Hello world\n");
i++;
}
return l;
}
how to solve main.cpp
This is called separate compilation and is commonly used in medium to large programs.
Here main.cpp could be as simple as:
int intf(void)
int main() {
intf();
return 0;
}
If you are using an IDE, just declare both source files in the same project, if you use a CLI compiler, just compile both into one executable. This could be the command on a Unix-like system:
c++ main.cpp function.cpp -o foo
But in that case you should learn what a makefile is...
This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 5 years ago.
I am experiencing something weird with my c++ source file or perhaps the compiler itself. It seems that when I attempt to compile the file, it hits me with a message -
undefined reference to "Basic_int_stack::Basic_int_stack()
undefined reference to "Basic_int_stack::Push(int)
Here is my code (I'm still a beginner so don't expect any crazy professional code )
Header file:
class Basic_int_stack
{
public:
// This part should be implementation independent.
Basic_int_stack(); // constructor
void push( int item );
int pop();
int top();
int size();
bool empty();
private:
// This part is implementation-dependant.
static const int capacity = 10 ; // the array size
int A[capacity] ; // the array.
int top_index ; // this will index the top of the stack in the array
};
Implementations:
#include "basic_int_stack.h"// contains the declarations of the variables and functions.
Basic_int_stack::Basic_int_stack(){
// the default constructor intitializes the private variables.
top_index = -1; // top_index == -1 indicates the stack is empty.
}
void Basic_int_stack::push( int item ){
top_index = top_index + 1;
A[top_index] = item ;
}
int Basic_int_stack::top(){
return A[top_index];
}
int Basic_int_stack::pop(){
top_index = top_index - 1 ;
return A[ top_index + 1 ];
}
bool Basic_int_stack::empty(){
return top_index == -1 ;
}
int Basic_int_stack::size(){
return top_index;
}
Main Function:
#include "basic_int_stack.h"
#include <iostream>
int main()
{
int var;
Basic_int_stack s1;
while((std::cin >> var)>=0){
s1.push(var);
}
return 0;
}
This is happening because you're building your main file without building and linking your class implementation file as well. You need to adjust your build settings somehow.
It is because you don't include Basic_int_stack.cpp when you complile.
Simplely speaking, when you encounter Undefined reference to xxx, it is a error generated by linker, when means the compliler can't find the implements. So you need check if you include the cpp file or dynamic library or static library.
I faced the same problem. Finally I found a fix by including .cpp file in the main file.
#include "file_name.cpp" //In the main file
I am trying to declare the functions in separate files. In the code given below, my main() is defined in main.cpp and the int addition(int x, int y) is defined
in an another file named function.cpp.
My code:
main.cpp
#include "function.cpp"
#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
int a = 1;
int b = 15;
int sum = addition(a,b);
cout<<"\nSum = "<<sum<<"\n";
return 0;
}
fucntion.cpp
int addition(int x, int y)
{
int sum = x + y;
return sum;
}
But by using the above cod in Eclipse i am getting the following error. On the other hand, if i compile the code manually using make
through the linux terminal then, the same got works.
ERROR:
/home/eclipse_workspace/multiFiles/Debug/../funtion.cpp:9: multiple definition of `addition(int, int)'
./funtion.o:/home/eclipse_workspace/multiFiles/Debug/../funtion.cpp:9: first defined here
collect2: ld returned 1 exit status.
First of all it is not recommended to include .cpp files. You should create header (.h) with declarations, put implementations to .cpp, like now and wherever you need to use it just include.h . You should also read about avoiding multiple includes by adding #ifndef/#define/#endif.
Update:
#include works in pre compiling phase and more or less it means "paste here what you have in file ...". So it copies function from one file and pastes to main file then compiles it. After this it compiles also cpp file with your function - also ok. Now comes linking: because of previous steps and copy-paste it has two definitions (actually two symbols) which has same name - that is causing the error and that's why we have headers :)
First create a header file, for example Addition.h and declare the function name inside it. Then make a file Addition.cpp and write the addition function implementation and then include the Addition.h in your main.cpp file.
The concept of using a header file is that you can use it anywhere else and is not limited to your main.cpp program file.
So, in short
Addition.h
class Addition { public:
int addition(int a , int b); //function declaration
private: int result_; };
then in Addition.cpp
#include Addition.h
int Addition::addition(int x, int y) {
// function implementation
}
in main.cpp
#include <Addition.h>
int main()
{ int a=3, b=4, sum=0;
Addition objAdd; //creation of object for class Addition
sum = objAdd.addition(a,b);
}
Hope this helps in structuring your code.
C language does not use name mangling like C++. This can lead to subtle bugs, when function prototype is declared differently in different files. Simple example:
/* file1.c */
int test(int x, int y)
{
return y;
}
/* file2.c */
#include <stdio.h>
extern int test(int x);
int main()
{
int n = test(2);
printf("n = %d\n", n);
return 0;
}
When compiling such code using C compiler (in my case gcc) no errors are reported. After switching to C++ compiler, linking will fail with error "undefined reference to 'test(int)'". Unfortunately in practice this is not so easy - there are cases when code is accepted by C compiler (with possible warning messages), but compilation fails when using C++ compiler.
This is of course bad coding practice - all function prototypes should be added to .h file, which is then included in files where function is implemented or used. Unfortunately in my app there are many cases like this, and fixing all of them is not possible in short term. Switching to g++ is also not at option, I got compilation error quite fast.
One of possible solutions would be to use C++ name mangling when compiling C code. Unfortunately gcc does not allow to do this - I did not found command line option to do this. Do you know if it is possible to do this (maybe use other compiler?). I also wonder if some static analysis tools are able to catch this.
Using splint catches these kinds of errors.
foo.c:
int test(int x);
int main() {
test(0);
}
bar.c:
int test(int x, int y) {
return y;
}
Running splint:
$ splint -weak foo.c bar.c
Splint 3.1.2 --- 20 Feb 2009
bar.c:1:5: Function test redeclared with 2 args, previously declared with 1
Types are incompatible. (Use -type to inhibit warning)
foo.c:4:5: Previous declaration of test
Finished checking --- 1 code warning
~/dev/temp$ cat > a.c
int f(int x, int y) { return x + y; }
~/dev/temp$ cat > b.c
extern int f(int x); int g(int x) { return f(x + x); }
~/dev/temp$ splint *.c
Splint 3.1.2 --- 03 May 2009
b.c:1:12: Function f redeclared with 1 arg, previously declared with 2
Types are incompatible. (Use -type to inhibit warning)
a.c:1:5: Previous declaration of f
Finished checking --- 1 code warning
~/dev/temp$
I cannot figure out why this is not working. I will put up all three of my files and possibly someone can tell me why it is throwing this error. I am using g++ to compile the program.
Program:
#include <iostream>
#include "h8.h"
using namespace std;
int main()
{
char sentence[MAX_SENTENCE_LENGTH];
char writeTo[] = "output.txt";
int distanceTo,likePosition, length, numWords;
cout << "ENTER A SENTENCE! ";
cin.getline(sentence, 299);
length = strlen(sentence);
numWords = wordCount(sentence, length);
for(int x = 0; x < 3; ++x)
{
likePosition = likePos(numWords);
distanceTo = lengthTo(sentence, likePosition, length);
insertLike(sentence, distanceTo, length, writeTo);
}
return 0;
}
Function file:
void insertLike(const char sentence[], const int lengthTo, const int length, char writeTo[])
{
char part1[MAX_SENTENCE_LENGTH], part2[MAX_SENTENCE_LENGTH];
char like[] = " like ";
for(int y = 0; y < lengthTo; ++y)
part1[y] = sentence[y];
for(int z = lengthTo+1; z < length - lengthTo; ++z)
part2[z] = sentence[z];
strcat(part1, like);
strcat(part1, part2);
writeToFile(sentence, writeTo);
return;
}
Header file:
void insertLike(const char sentence[], const int lengthTo, const int length, const char writeTo[]);
The error exactly is:
undefined reference to 'insertLike(char const*, int, int, char const*)'
collect2: ld returned 1 exit status
The declaration and definition of insertLike are different
In your header file:
void insertLike(const char sentence[], const int lengthTo, const int length, const char writeTo[]);
In your 'function file':
void insertLike(const char sentence[], const int lengthTo, const int length,char writeTo[]);
C++ allows function overloading, where you can have multiple functions/methods with the same name, as long as they have different arguments. The argument types are part of the function's signature.
In this case, insertLike which takes const char* as its fourth parameter and insertLike which takes char * as its fourth parameter are different functions.
Though previous posters covered your particular error, you can get 'Undefined reference' linker errors when attempting to compile C code with g++, if you don't tell the compiler to use C linkage.
For example you should do this in your C header files:
extern "C" {
...
void myfunc(int param);
...
}
To make 'myfunc' available in C++ programs.
If you still also want to use this from C, wrap the extern "C" { and } in #ifdef __cplusplus preprocessor conditionals, like
#ifdef __cplusplus
extern "C" {
#endif
This way, the extern block will just be “skipped” when using a C compiler.
You need to compile and link all your source files together:
g++ main.c function_file.c
This could also happen if you are using CMake. If you have created a new class and you want to instantiate it, at the constructor call you will receive this error -even when the header and the cpp files are correct- if you have not modified CMakeLists.txt accordingly.
With CMake, every time you create a new class, before using it the header, the cpp files and any other compilable files (like Qt ui files) must be added to CMakeLists.txt and then re-run cmake . where CMakeLists.txt is stored.
For example, in this CMakeLists.txt file:
cmake_minimum_required(VERSION 2.8.11)
project(yourProject)
file(GLOB ImageFeatureDetector_SRC *.h *.cpp)
### Add your new files here ###
add_executable(yourProject YourNewClass.h YourNewClass.cpp otherNewFile.ui})
target_link_libraries(imagefeaturedetector ${SomeLibs})
If you are using the command file(GLOB yourProject_SRC *.h *.cpp) then you just need to re-run cmake . without modifying CMakeLists.txt.
If you are including a library which depends on another library, then the order of inclusion is also important:
g++ -o MyApp MyMain.o -lMyLib1 -lMyLib2
In this case, it is okay if MyLib1 depends on MyLib2.
However, if there reverse is true, you will get undefined references.
As Paul said, this can be a linker complaint, rather than a compiler error. If you read your build output/logs carefully (may need to look in a separate IDE window to see the full details) you can dell if the problem is from the compiler (needs to be fixed in code) or from the linker (and need to be fixed in the make/cmake/project level to include a missing lib).