I am trying to solve a problem set from cs50's course, however, when I try to run the following code on my desktop version of Visual Studio Code, I get a compilation error.
#include <stdio.h>
#include <string.h>
#include "cs50.h"
// Max number of candidates
#define MAX 9
// Candidates have name and vote count
typedef struct
{
string name;
int votes;
}
candidate;
// Array of candidates
candidate candidates[MAX];
// Number of candidates
int candidate_count;
// Function prototypes
bool vote(string name);
void print_winner(void);
int main(int argc, string argv[])
{
// Check for invalid usage
if (argc < 2)
{
printf("Usage: plurality [candidate ...]\n");
return 1;
}
// Populate array of candidates
candidate_count = argc - 1;
if (candidate_count > MAX)
{
printf("Maximum number of candidates is %i\n", MAX);
return 2;
}
for (int i = 0; i < candidate_count; i++)
{
candidates[i].name = argv[i + 1];
candidates[i].votes = 0;
}
int voter_count = get_int("Number of voters: ");
// Loop over all voters
for (int i = 0; i < voter_count; i++)
{
string name = get_string("Vote: ");
// Check for invalid vote
if (!vote(name))
{
printf("Invalid vote.\n");
}
}
// Display winner of election
print_winner();
}
// Update vote totals given a new vote
bool vote(string name)
{
// TODO
for (int i=0;i<candidate_count;i++){
if(!strcmp(name,candidates[i].name)){
candidates[i].votes +=1;
return true;
}
}
return false;
}
// Print the winner (or winners) of the election
void print_winner(void)
{
// TODO
int max=0;
string max_name = "";
for (int i=0;i<candidate_count;i++){
if(max<candidates[i].votes){
max = candidates[i].votes;
strcpy(max_name,candidates[i].name);
}
}
for (int i=0; i<candidate_count;i++){
if(candidates[i].votes==max){
printf("%s\n",candidates[i].name);
}
}
return;
}
Following Error shows up at the terminal;
* Executing task: C/C++: gcc.exe build active file
Starting build...
C:/msys64/mingw64/bin/gcc.exe -fdiagnostics-color=always -g D:\Work\C-Language\Plurality.c -o D:\Work\C-Language\Plurality.exe
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\Admin\AppData\Local\Temp\ccrzNxos.o: in function `main':
D:/Work/C-Language/Plurality.c:49: undefined reference to `get_int'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe: D:/Work/C-Language/Plurality.c:53: undefined reference to `get_string'
collect2.exe: error: ld returned 1 exit status
Build finished with error(s).
I have set up my Visual Studio Code for C/C++ using the following link; https://code.visualstudio.com/docs/languages/cpp
The Terminal shows that the program can not compile the external header file simultaneously, can you please guide me through this because it is my first time using VS Code for C/C++, previously I used to work on Dev C++, if there is some specific config: you would want to suggest for using VS Code for C/C++ programs, it will be appreciated.
Thank you.