LNK2019 error with Linked Lists ( c programming) - singly-linked-list

I'm new at c programming, and during my learnings, lately I've started to deal with Linked lists. In this program that I wrote, i keep getting this message( LNK2019 error):
unresolved external symbol _main referenced in function "int __cdecl invoke_main(void)" (?invoke_main##YAHXZ)
What I'm trying to do is to create a linked list, and use a function to input values into this list, using the main.
this is the full code I wrote:
#include <stdio.h>
#include <stdlib.h>
typedef struct Original_list
{
int data;
struct Original_list *next;
}original_list;
original_list *Input();
void EX2()
{
original_list *list;
list = Input();
}
original_list *Input()
{
original_list *lst, *curr_point;
int c;
printf("Please enter a value to the first data: \n");
scanf_s("%d", &c);
if (c < 0)
return NULL;
lst = (original_list*)malloc(sizeof(original_list));
curr_point = lst;
lst->data = c;
while (c >= 0)
{
curr_point->next = (original_list*)malloc(sizeof(original_list));
curr_point = curr_point->next;
curr_point->data = c;
printf("please enter number(scan will stop if a negative number is scanned): \n");
scanf_s("%d", &c);
}
curr_point->next = NULL;
return lst;
}
I can't see any definition I did wrong or any problem justifying this error.
please help!
thank you very much!

Your code lacks an entry point. For C/C++ it is usually main(), that's what the error is about.

Check the projects configuration and make sure that you have set
Linker > System > Subsystem
to 'Console'. The issue occurs when it is set to 'Windows'.

Related

Problems with functions in classes C++ (LNK2019 & LNK1120 errors)

I've been working on a project for my college class that uses classes in c++, unfortunately anytime I try to call on a function that is passed parameters within my class the program fails to compile with the two following errors:
Error LNK2019 unresolved external symbol "int __cdecl binsearch(class Course * * const,int,char * const)" (?binsearch##YAHQAPAVCourse##HQAD#Z) referenced in function _main Project1 C:\Users\cvos\source\repos\Project1\Project1\courses_main.obj 1
and
Error LNK1120 1 unresolved externals Project1 C:\Users\cvos\source\repos\Project1\Debug\Project1.exe 1
I've looked up the LNK problems, and most results suggest it's something related to symbols in c++ vs c (That fix doesn't work) or that there is a problem with linking the files within visual studio (That fix also didn't work), and finally that it was something to do with it needing to be on the console subsystem (Which it already was).
The strange thing is, if I comment out my calls to all of the functions I've made in the "Course" class that are passed parameters, the program runs fine. It's only when I am trying to use the functions created in the "Course" class that the program fails to run, leading me to suspect strongly I'm doing something wrong with how I'm passing variables to my member functions.
I'll post the relevant parts of my code:
Within my header file "courses.h" I declare my function:
int binsearch(Course* co_ptr[], int size, char search[]);
Within my 2nd source file "courses_functions.cpp" I define the function:
int Course::binsearch(Course* co_ptr[], int size, char search[])
{
int low = 0, high = size - 1, first_index = -1, last_index = -1, num_of_entries = 0;
while (low <= high)
{
int mid = (low + high) / 2;
if (co_ptr[mid]->name == search)
{
bool found = false;
int i = mid;
while (!found) //Check values below mid
{
if (co_ptr[i]->name == search)
{
first_index = i; //first_index now holds a potential first occurence of our name
if (i == 0)
{
found = true;
}
}
else
{
found = true;
}
i--; //decrement i and check again.
}
i = mid; //Reset i
found = false; //Reset found
while (!found) //Check values above mid
{
if (co_ptr[i]->name == search)
{
last_index = i; //last_index now holds a potential last occurence of our name
if (i == size - 1)
{
found = true;
}
}
else
{
found = true;
}
i++; //increment i and check again.
}
break; //Breaks us out of the main while loop
}
else if (co_ptr[mid]->name < search)
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
if ((first_index != -1) && (last_index != -1))
{
for (int i = first_index; i <= last_index; i++)
{
std::cout << "\nEntry found: "
<< std::endl << co_ptr[i]->name << ' ' << co_ptr[i]->units << " units, grade:" << co_ptr[i]->grade;
num_of_entries++;
}
return num_of_entries;
}
else
{
std::cout << "\nEntry not found.";
return num_of_entries;
}
}
Lastly in my main source file "courses_main.cpp" I call the function:
else if (selection == 3) //Display a course
{
char title[50] = "";
int results = 0;
std::cout << "\nEnter a class to search for: ";
std::cin.getline(title, 50, '\n');
std::cin.ignore();
results = binsearch(courses, size, title);
}
As this is for a college class, I'm not looking to use any alternative methods, I'm mainly trying to figure out why the method I'm using would return the errors I shared above, but I will gladly post more snippets of my code if it is necessary.
Thanks!
The cause is almost certainly one of the following:
You're not compiling the implementation file (just using the header elsewhere).
You're compiling the implementation, but not using the compiled object in the linking of objects into the executable.
You have some minor mismatch in naming, e.g. using binsearch() not in a class context, or using a slightly different signature somehow (not likely giving what you've told us).
Need to see a declaration of your "courses.h" file. You may have declared binsearch outside of your Course class declaration. In which case you will get a linker error as mentioned.
Based on your usage in main.. your implementation of this function need not be in Course class, it can be a standalone function outside of Course class. once you move your function definition outside of Course class, your linker should go away, provided you have courses_functions.cpp and courses_main.cpp files in same project in your MSVC IDE.

error LNK2019: unresolved external symbol, cannot not link with the cpp file i coded [duplicate]

This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 7 years ago.
I start learning C++ in school and this error appear.
1>Bettle_Dice.obj : error LNK2019: unresolved external symbol "public: int __thiscall Beetle::checkcom(void)" (?checkcom#Beetle##QAEHXZ) referenced in function _main
I have include other header files and cpp files, I don understand why only this file have problem please help
Below is my code
main.cpp
#include "stdafx.h"
#include "beetle.h"
#include "dice.h"
#include "player.h"
#include <iostream>
using namespace std;
int main()
{
Player p; //declare Class to a variable
Dice d;
Beetle btle;
int temp;
cout << "Number of players?" << endl;
cin >> temp;
p.Num(temp); //store the number of player into class
//cout << p.getNumPlayers() <<endl;
cout << "Start game!!" <<endl;
temp = btle.checkcom();
while(temp != 1)
{
for(int i=0;i<p.getNumPlayers();i++)
{
temp = d.roll();
cout <<"Your roll number:"<< temp;
}
}
return 0;
}
beetle.h
class Beetle
{
private:
int body,head,ante,leg,eye,tail;
public:
int completion();
int checkcom();
int getBody() { return body;};
int getHead() { return head;};
int getAnte() { return ante;};
int getLeg() { return leg;};
int getEye() { return eye;};
int getTail() { return tail;};
};
Beetle.cpp
#include "stdafx.h"
#include "beetle.h"
int completion()
{
return 0;
}
int checkcom()
{
Beetle btle;
int flag = 0;
if(btle.getBody() == 1 && btle.getHead() == 1 && btle.getAnte() == 2 && btle.getEye() == 2 && btle.getLeg() ==6 && btle.getTail() == 1)
flag = 1;
return flag;
}
I checked some solution on the internet, some are saying is the library problem, but this file is not a built-in function. I guess it is not the problem of the library. I tried to include the beetle.obj file to it and the debugger said it is included already and duplicate definition.
In the other file, i do not have "bettle" this word. It should not be the problem of double declaration or duplicate class.
I have no idea what the problem is. Please help.
You need to prefix the signature of your class functions with the class name Beetle::
Otherwise the compiler just thinks those functions are global functions, not member functions.

C++: Unresolved Externals in MP3 assignment

I'm working on a MP3 player for an assignment. I keep getting the following errors:
1>A4_main.obj : error LNK2019: unresolved external symbol "public: static void __cdecl Song::ClearListFile(void)" (?ClearListFile#Song##SAXXZ) referenced in function "void __cdecl DeleteSong(void)" (?DeleteSong##YAXXZ)
1>A4_main.obj : error LNK2001: unresolved external symbol "public: static char * Song::songListFile_" (?songListFile_#Song##2PADA)
1>A4_Song.obj : error LNK2001: unresolved external symbol "public: static char * Song::songListFile_" (?songListFile_#Song##2PADA)
1>A4_Song.obj : error LNK2019: unresolved external symbol __imp__mciSendStringA#16 referenced in function "public: void __thiscall Song::PlaySong(void)" (?PlaySong#Song##QAEXXZ)
1>A4_Song.obj : error LNK2001: unresolved external symbol "public: static char * Song::currentMP3_" (?currentMP3_#Song##2PADA)
From what I understand, these sort of errors stem from not including function declarations, declaring but not implementing them, misspelling, etc. What have I missed here? Since this is an assignment, I'll post the bare minimum of the code I think is causing the problem.
A4_main.cpp
#include "A4_LinkedList.h"
#include "A4_Song.h"
#include <iostream>
#include <fstream>
#include <cstdio>
#include <string>
using namespace std;
LinkedList g_list;
void FreeLinkedList();
char DisplayMenu();
void LoadSongFile();
void AddNewSong();
void DeleteSong();
void PlaySong();
void PrintAllSongs();
//stuff
void LoadSongFile()
{
const int SZ = 256;
int songCnt = 0;
ifstream inData;
char buff[SZ];
Song* newSong;
_flushall();
cout << "\nEnter the full file path: ";
cin.getline(Song::songListFile_, SZ);
// Open the file
inData.open(Song::songListFile_);
// Free any memory currently allocated for the word array
FreeLinkedList();
// Loop through file again and allocate memory
while (!inData.eof())
{
// Each time through loop read all 5 entries in each line.
// Songt with the Song name
inData.getline(buff, SZ);
if (buff[0] == 0)
{
// No more words
break;
}
// Create a new Song object
newSong = new Song(buff);
if (newSong == 0)
{
cout << "\nDynamic memory allocation failed.";
break;
}
// Add this Song object to the linked list
g_list.AddLinkToBack(newSong);
songCnt++;
}
inData.close();
cout << "\nLoaded file and read " << songCnt << " Song objects.";
}
void DeleteSong()
{
const int SZ = 256;
bool foundSong = false;
Node* node = g_list.GetFirstNode();
Song* song = 0;
char songFileName[SZ];
_flushall();
// Prompt the user for the name of a song
cout << "\nEnter the song name with extension: ";
cin.getline(songFileName, SZ);
// Loop through the linked list for that song and delete it if it is found.
// If not, print error to console.
while (node != 0)
{
// Cast the void ptr to a song object ptr
song = (Song*)(node->data_);
// Call on the Song class to print the objects contents
if (strcmp(song->GetSongName(), songFileName) == 0)
{
// Set flag and get out of loop
g_list.RemoveThisLink(node);
foundSong = true;
break;
}
// Go to the next node
node = node->next_;
}
if (!foundSong)
{
cout << "\nCould not find that song in list!\n";
}
else
{
// Now that the linked list has been updated need to persist the new
// list to the song file, replacing previous contents.
Song::ClearListFile();
// Now loop through the linked list again, appending the song
// file name to the song list file.
node = g_list.GetFirstNode();
while (node != 0)
{
// Cast the void ptr to a song object ptr then add name to file
song = (Song*)(node->data_);
song->AppendToListFile();
// Go to the next node
node = node->next_;
}
}
}
A4_Song.cpp
#include "A4_Song.h"
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <Windows.h>
using namespace std;
// Store the path name of the song list file
static char songListFile_[ENTRY_SZ] = "";
static char currentMP3_[ENTRY_SZ] = "";
// Static method to empty the song list file
static void ClearListFile()
{
ofstream outFile;
if (songListFile_[0] != 0)
{
// Open for truncate then close again
outFile.open(songListFile_, ios_base::ate);
outFile.close();
}
else
cout << "\nNothing to clear!";
}
void Song::PlaySong()
{
const int BUFF_SZ = 512;
char fullStr[BUFF_SZ];
MCIERROR err;
StopSong();
// Set global variable so we know this file is playing.
// Sandwich the file name in escaped double quotes so
// spaces can be included and don't need to double up
// on the backslashes.
sprintf_s(currentMP3_, ENTRY_SZ, "\"%s\"", songPath_);
sprintf_s(fullStr, BUFF_SZ, "open %s type mpegvideo alias myFile", currentMP3_);
err = mciSendString(fullStr, NULL, 0, 0);
err = mciSendString("play myFile", NULL, 0, 0);
}
Let me know if I've omitted too much.
Your problem is that you have variables and functions declared inside Song, but are defined at namespace level. This makes them different entities, and so definitions for the declarations in Song are never found.
static char songListFile_[ENTRY_SZ] = "";
static char currentMP3_[ENTRY_SZ] = "";
static void ClearListFile() {/*...*/}
These should be changed. Removing static and prefixing the surrounding class Song should fix it.
char Song::songListFile_[ENTRY_SZ] = "";
char Song::currentMP3_[ENTRY_SZ] = "";
void Song::ClearListFile() {/*...*/}
You only need the static inside the class definition. Outside it, you're using a different meaning of the static keyword. I think you have more instances like this outside the code you posted, but it shouldn't be difficult to find them.

Error Code LNK2019 & LNK1120 [duplicate]

This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 7 years ago.
I create this file over and over and cant seem to see why I'm getting this error. I tried going to the line where the code is but the format seem correct I may just need another set of eyes .
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
void readString(char*, int);
void changeToUppercase(char*, int);
void displayStringInUppercase(char*, int);
int main()
{
int arraySize;
char* characterArray;
cout << "Enter the size of dynamic array: ";
cin >> arraySize;
characterArray = new char[arraySize];
readString(characterArray, arraySize);
changeToUppercase(characterArray, arraySize);
displayStringInUppercase(characterArray, arraySize);
delete [] characterArray;
system ("pause");
return 0;
}
void changeToUppercase(char* characterArray, int arraySize)
{
for(int i = 0; i < arraySize; i++)
characterArray[i] = toupper(characterArray[i]);
}
void displayStringInUppercase(char* characterArray, int arraySize)
{
cout << "\nThestring inupper case letters: ";
for(int i = 0; i < arraySize; i++)
characterArray[i] = toupper(characterArray[i]);
}
This is the error codes that keep popping up:
error LNK2019: unresolved external symbol "void __cdecl readString(char *,int)" (?readString##YAXPADH#Z) referenced in function _main
fatal error LNK1120: 1 unresolved externals
You use a forward declaration: void readString(char*, int); but then never actually define this function.
Define your readString function later in your code like...
void readString(char* str, int a)
{
// do stuff
}
You are missing the readString function. You have a forward declaration that satisfies the compiler here
void readString(char*, int);
But no actual implementation of the function to satisfy the linker when it tries to put your program together. You need something along the lines of
void readString(char* characterArray, int arraySize)
{
// do stuff here
}

Linking error while using static library linkage

This might have been asked previously, however, I found it only in context of Classes, and this is not the case.
Utils.h
#ifndef _UTILS_H_
#define _UTILS_H_
#include <cmath>
//is 'x' prime?
bool isPrime(long long int x);
//find the number of divisors of 'x' (including 1 and x)
int numOfDivisors(long long int x);
#endif //_UTILS_H_
Utils.cpp
#include "Utils.h"
bool isPrime(long long int x){
if (x < 2){
return false;
}
long double rootOfX = sqrt( x );
long long int flooredRoot = (long long int)floor ( rootOfX );
for (long long int i = 2; i <= flooredRoot; i++){
if (x % i == 0){
return false;
}
}
return true;
}
int numOfDivisors(long long int x){
if (x == 1){
return 1;
}
long long int maxDivisor = (x / 2) + 1;
int divisorsCount = 0;
for (long long int i = 2; i<=maxDivisor; i++){
if (x % i == 0){
divisorsCount++;
}
}
divisorsCount += 2; //for 1 & x itself
return divisorsCount;
}
These two files have been compiled with Visual Studio 2012 in Debug mode as a static library.
Now I try to use them in a separate project, let's call it MainProject:
1. Add the "Utils.vcproj" to MainProject solution.
2. Make MainProject to depend on Utils
3. In "Properties"->"Linker"->"Input"->"Additional Dependencies" put the path to Utils.lib
Here is the main which uses Utils:
#include <iostream>
#include "..\Utils\Utils.h"
using namespace std;
int main(){
cout << "num of divisors of " << 28 << ": " << numOfDivisors(28) << endl;
//this part is merely to stop visual studio and look at the output
char x;
cin >> x;
return 0;
}
And this is the error I get:
Error 1 error LNK2019: unresolved external symbol "int __cdecl numOfDivisors(__int64)" (?numOfDivisors##YAH_J#Z) referenced in function _main G:\ProjectEuler\Problem12\Source.obj Problem12
Why can't it find the code which implements "numOfDivisors"? I have given it the .lib which contains it, moreover - put a dependency on the Utils project itself...
Any help would be appreciated.
Assuming the library is correctly built and linked, the next most likely cause of the error is that the function is named something else in the library than it is in the code that links to it.
This could be caused by any number of project settings that affect either name decoration or type names. There's not really any point in guessing from a distance which particular setting is the culprit in your case. You can compare the two projects' properties (either manually or with a diff tool) and try to spot a difference that would result in a different decorated function name.
Looks like method numOfDivisors() is not defined in you Utils.cpp, can you check it once?
And why is your compiler complaining "G:\ProjectEuler\Problem12\Source.obj"? Where is Source.obj coming from?
You have to specify library path in one field and library name in other field, have you specified both under appropriate settings?