How to compile multiple C files in code blocks - c

So I was originally writing my code in code blocks but when I'd try to compile it would always give me errors saying that it wasn't understanding the references i was making to functions in other files.At which point I starting using atom, but it's come to the point where I need to use he debugging tool in code blocks and I'm still getting the same errors even though my code compiles when I run it through gcc. Can someone help please?? These are the errors I'm getting.
||=== Build: Debug in A2 (compiler: GNU GCC Compiler) ===|
obj\Debug\main.o||In function main':|
main.c|18|undefined reference tocreateMyVector'|
main.c|29|undefined reference to PathInit'|
main.c|30|undefined reference toAllPathsRec'|
main.c|31|undefined reference to `PathPrint'|
||=== Build failed: 4 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "vector.h"
#include "path.h"
#define BUFFERSIZE 20
int main()
{
Vector *leVector;
unsigned int size;
char leArray[BUFFERSIZE];
scanf("%u\n",&size);
fgets(leArray,sizeof(leArray),stdin);
leVector = createMyVector(size);
char *element = strtok(leArray, " ");
int i;
for(i=0;i<size;i++){
*(leVector->item + i) = atoi(element);
element = strtok(NULL," ");
}
Path Solution;
PathInit(&Solution,size);
AllPathsRec(0,leVector,&Solution);
PathPrint(&Solution);
return 0;
}
vector.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "vector.h"
void vectorRead(Vector * V){
printf("Size of the array is: %d\n",V->size);
int i;
for(i = 0; i < V->size; i++){
if(i == V->size)
printf("%d\n ",*(V->item+i));
else
printf("%d ",*(V->item+i));
}
}
Vector * createMyVector(int size){
Vector * vect = (Vector *)malloc(sizeof(Vector));
vect->size = size;
vect->item = (int *)malloc(sizeof(int)*size);
return vect;
}
path.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "vector.h"
#include "path.h"
void PathInit(Path *P, int vsize){
P->size = vsize;
P->item = (int *)malloc(sizeof(int)*vsize);
P->top = -1;
}
int AllPathsRec(int position, Vector *V, Path *Solution){
PathAddEntry(Solution,position);
position += *(V->item + position);
while(Solution->top != V->size -1){
AllPathsRec(position, V, Solution);
}
return 0;
}
int PathAddEntry(Path *P, int entry){
if(P->top >= P->size - 1){
printf("ERROR: STACK OVERFLOW\n");
return 1;
}
P->top++;
*(P->item + P->top) = entry;
return 0;
}
int PathRemoveEntry(Path *P){
if(P->top <= -1){
printf("\nERROR: NO ELEMENT TO REMOVE\n");
return 1;
}
P->top--;
return 0;
}
void PathPrint(Path *P){
printf("Size of the Solution array is: %d\n",P->size);
int i;
for(i = 0;i <= P->top; i++){
if(i == P->top)
printf("%d\n ", *(P->item+i));
else
printf("%d ", *(P->item+i));
}
}
vector.h
#ifndef VECTOR_H
#define VECTOR_H
typedef struct {
int size;
int *item;
}Vector;
Vector * createMyVector(int size);
void vectorRead(Vector * V);
#endif
path.h
#ifndef PATH_H
#define PATH_H
typedef struct{
int size;
int top;
int *item;
}Path;
void PathInit(Path *P, int size);
int AllPathsRec(int position, Vector *V, Path *Solution);
int PathAddEntry(Path *P, int entry);
int PathRemoveEntry(Path *P);
void PathPrint(Path *P);
#endif

Related

Expected identifier or '(' parse issue in C language in Xcode

I was working on pop and push methods on the stack. Actually in this code I am creating dynamic array using pointers and malloc function. Then I was trying to add or delete elements to dynamic array with pop and push methods.But I getting the error in the question. I can't see any error in the code. Can you help me?
Here my main.c file
#include <stdio.h>
#include <stdlib.h>
#include "main_header.h"
stack * init(){
stack *s = (stack *) malloc(sizeof(stack));
s->items = NULL;
s->top = 0;
s->count = 2;
return s;
}
int pop(stack *s){
if(s->items == NULL){
printf("Items is empty.\n");
return -1;
}
if(s->top<=s->count/4){
int *items2 = (int *)malloc(sizeof(int)*s->count/2);
for (int i = 0; i < (s->count/2); i++){
items2[i] = s->items[i];
}
free(s->items); // burada "dizi" adındaki dizimiz dizi2 ile aynı yeri gösterdiğinde önceki 2 elemanlık dizi lost in space olacak bunu önlemek için free(dizi) diyerek o 2 elemanı bellekten siliyoruz.
s->items = items2;
s->count /= 2;
}
return s->items[--s->top];
}
void push(int a, stack *s){
if(s->items == NULL){
s->items = (int *)malloc(sizeof(int) * 2);
}
if(s->top>=s->count){
int *items2 = (int *)malloc(sizeof(int)*s->count*2);
for (int i = 0; i < s->count; i++)
items2[i] = s->items[i];
free(s->items); // burada "dizi" adındaki dizimiz dizi2 ile aynı yeri gösterdiğinde önceki 2 elemanlık dizi lost in space olacak bunu önlemek için free(dizi) diyerek o 2 elemanı bellekten siliyoruz.
s->items = items2;
s->count *= 2;
}
s->items[s->top++] = a;
}
void getItems(stack *s){
printf("count: %d\n", s->count);
for (int i = 0; i < s->top; i++) {
printf("%d\n", s->items[i]);
}
}
main_header.h file
#ifndef main
#define main
struct s {
int count;
int top;
int *items;
};
typedef struct s stack;
stack * init(void);
int pop(stack *);
void getItems(stack *);
void push(int, stack *);
#endif
test_stack.c file
#include <stdio.h>
#include <stdlib.h>
#include "main_header.h"
int main(){
stack *s1 = init();
stack *s2 = init();
for (int i = 0; i < 10; i++) {
push(i*10, s1);
}
getItems(s1);
for (int i = 0; i < 10; i++) {
push(pop(s1), s2);
}
return 0;
}
After #define main in “main_header.h”, the code int main(){ in “test_stack.c” is replaced by int (){. This causes the syntax error that the compiler (not Xcode) reports.
Do not use main in “main_header.h” as an indicator for whether the header file has been included already. Use some other name that you will not use for anything else, such as main_h or main_header_h.
(Clang is the compiler. Xcode is the overall integrated development environment that facilitates use of the compiler, organizes your projects files, opens editors, maintains your project options, and so on.)

Multi-threading using Merge sort

I am newly starting using Linux in Ubuntu and am trying to code a multi-threading merge sort but some kind of errors are showing on Windows terminal.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <pthread.h>
struct Params
{
int *start;
size_t len;
int depth;
};
pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
void *merge_sort_thread(void *pv);
void merge(int *start, int *mid, int *end)
{
int *res = malloc((end -start)*sizeof(*res));
int *lhs = start, *rhs = mid, *dst = res;
while (lhs != mid && rhs != end)*dst++ = (*lhs <= *rhs) ? *lhs++ : *rhs++;
while (lhs != mid)*dst++ = *lhs++;
while (rhs != end)*dst++ = *rhs++;
memcpy(start, res, (end -start)*sizeof(*res));free(res);
}
void merge_sort_mt(int *start, size_t len, int depth)
{
if (len < 2)return;
if (depth <= 0 || len < 4)
{
merge_sort_mt(start, len/2, 0);
merge_sort_mt(start+len/2, len-len/2, 0);
}
else{
struct Params params = { start, len/2, depth/2 };
pthread_t thrd;pthread_mutex_lock(&mtx);
printf("Starting subthread...\n");
pthread_mutex_unlock(&mtx);
pthread_create(&thrd, NULL, merge_sort_thread, &params);
merge_sort_mt(start+len/2, len-len/2, depth/2);
pthread_join(thrd, NULL);
pthread_mutex_lock(&mtx);
printf("Finished subthread.\n");
pthread_mutex_unlock(&mtx);
}
merge(start, start+len/2, start+len);
}
void *merge_sort_thread(void *pv)
{
struct Params *params = pv;
merge_sort_mt(params->start, params->len, params->depth);
return pv;
}
void merge_sort(int *start, size_t len)
{
merge_sort_mt(start, len, 4);
}
int main()
{
static const unsigned int N = 2048;
int *data = malloc(N * sizeof(*data));
unsigned int i;
srand((unsigned)time(0));
for (i=0; i<N; ++i)
{
data[i] = rand() % 1024;
printf("%4d ", data[i]);
if ((i+1)%8 == 0)
printf("\n");
}
printf("\n");
merge_sort(data, N);
for (i=0; i<N; ++i)
{
printf("%4d ", data[i]);
if ((i+1)%8 == 0)
printf("\n");
}
printf("\n");
free(data);
return 0;
}
Here, is the .c code of multithreadind but not complete the program due to errors.
Here below, is the errors..
/tmp/ccTNp3Yz.o: In function `merge_sort_mt':
OS.c:(.text+0x213): undefined reference to `pthread_create'
OS.c:(.text+0x269): undefined reference to `pthread_join'
collect2: error: ld returned 1 exit status
If any library or any correction in code please tell and please add some important libraries which is usually used in terminal like sudo
As was stated at the comment above, you need to link your program with pthread library.
add -lpthread to your link command.

how we can define and use structure inside function in C?

I am trying to create a structure inside a function and i am trying to use it. But when I am comparing two values from structure I am getting this message :
"C:\Users\hp\Desktop\prgm\cap.c||In function 'fnumber':|
C:\Users\hp\Desktop\prgm\cap.c|
72|error: request for member 'f_value' in something not a structure or union|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
this is my code:-
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
/*
* Complete the function below.
*/
int fnumber(long input1,int input2_size, int* input2)
{
int i, j, k, count[input2_size],temp=0;
int arr_temp[input2_size];
struct smaller{
int position;
int f_value;};
struct smaller list[input2_size];
struct smaller temp1;
memccpy(arr_temp, input2, input2_size,sizeof(int));
for(i=0; i<input2_size;i++)
{
for(j=i+1; j<=input2_size;i++)
{
if(arr_temp[i]>arr_temp[j])
{
temp=arr_temp[i];
arr_temp[i]=arr_temp[j];
arr_temp[j]=temp;
}
}
}
for(i=0; i<input2_size;i++)
{
if(i>1)
count[i]=input2[i];
for(j=0;j<input2[i-1];j++)
{
count[i]+=arr_temp[j];
}
}
/* for(i=0;i<input2_size-1;i++)
{
for(j=i+1;j<input2_size;j++)
{
if(count[i]>count[j])
{
temp=count[i];
count[i]=count[j];
count[j] = temp;
}
}
}*/
for(i=0,j=0;i<input2_size;i++)
{
if(count[i]<=input1)
continue;
else
{
list[j].position=i;
list[j].f_value=count[i];
j++;
}
}
for(i=0;i<input2_size-1;i++)
{
for(j=i+1;j<input2_size;j++)
{
if(list[i].f_value>list[j.f_value])
{
temp1=list[i];
list[i]=list[j];
list[j]=temp1;
}
}
}
return list[0].position;
}
int main() {
int output = 0;
long ip1;
scanf("%ld", &ip1);
int ip2_size = 0;
int ip2_i;
scanf("%d\n", &ip2_size);
int ip2[ip2_size];
for(ip2_i = 0; ip2_i < ip2_size; ip2_i++) {
int ip2_item;
scanf("%d", &ip2_item);
ip2[ip2_i] = ip2_item;
}
output = fnumber(ip1,ip2_size,ip2);
printf("%d\n", output);
return 0;
}
if(list[i].f_value>list[j.f_value])
You misspelled list[j].f_value as list[j.f_value].
Also, memccpy should be memcpy.

Program stops responding when initializing a variable

I'm having a problem that must be idiot, but I can't see why.
the main code reaches the "2test" print and then stops responding at l->n = 0;
This is my first (real) program in C, so my knowledge is small in this language.
main.c:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "list.h"
int main(){
TList* l;
FILE* txt = fopen("arqtxt.txt", "r");
char aux[80];
int c = fgetc(txt), x = 0;
printf("1test");
TList_Init(l);
printf("6test");
while ((c = fgetc(txt)) != EOF){
printf("%d",c);
while (!(isalpha(c))) c = fgetc(txt);
if (isupper(c)) c = c+32;
if (islower(c)) aux[x++] = (char) c;
else{
TList_Insert(l, aux);
strcpy(aux, "");
}
}
TList_Print(l);
getchar();
return 0;
}
list.c:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "list.h"
void TList_Init (TList* l){
printf("2test");
l->n = 0;
printf("3test");
l->tam = 100;
printf("4test");
l->v = malloc(sizeof(TItem)*l->tam);
printf("5test");
}int TList_Search (TList* l, char* c){
int i;
for (i = l->n-1; i >= 0; i--)
if (strcmp(l->v[i].chave, c) == 0) return i;
return -1;
}
void InsertSort (TItem* v, int n){
int i,j;
TItem aux;
for (i = 1; i < n; i++){
aux = v[i];
j = i-1;
while (j >= 0 && strcmp(aux.chave, v[j].chave) < 0){
v[j+1] = v[j];
j--;
}
v[j+1] = aux;
}
}
void TList_Insert (TList* l, char word[80]){
if (l->n == l->tam){
l->tam += 100;
l->v = realloc(l->v, sizeof(TItem)*l->tam);
}
char* c = malloc(sizeof(char)*strlen(word));
c = word;
int aux = TList_Search(l, c);
if (aux != -1){
l->v[aux].no++;
return;
}
l->v[l->n].chave = c;
l->v[l->n].no = 1;
l->n++;
InsertSort(l->v, l->n);
}
void TList_Print (TList* l){
int x;
for (x = 0; x <= l->n; x++)
printf("%s - %d", l->v[x].chave, l->v[x].no);
}
list.h:
#ifndef LIST_H_
#define LIST_H_
typedef struct Item{
char* chave;
int no;
} TItem;
typedef struct List{
TItem* v;
int n, tam;
} TList;
void TList_Init (TList*);
void TList_Insert (TList*, char[]);
void TList_Print (TList*);
#endif
output:
||=== Build: Debug in EP1 (compiler: GNU GCC Compiler) ===|
C:\Users\Lucas\Desktop\EP1\main.c||In function 'main':|
C:\Users\Lucas\Desktop\EP1\main.c|13|warning: 'l' is used uninitialized in this function [-Wuninitialized]|
||=== Build finished: 0 error(s), 1 warning(s) (0 minute(s), 0 second(s)) ===|
||=== Run: Debug in EP1 (compiler: GNU GCC Compiler) ===|
-------------- Run: Debug in EP1 (compiler: GNU GCC Compiler)---------------
Checking for existence: C:\Users\Lucas\Desktop\EP1\bin\Debug\EP1.exe
Executing: "C:\Program Files (x86)\CodeBlocks/cb_console_runner.exe" "C:\Users\Lucas\Desktop\EP1\bin\Debug\EP1.exe" (in C:\Users\Lucas\Desktop\EP1\.)
Process terminated with status -1073741510 (0 minute(s), 9 second(s))
To expand on Jens' correct answer: TList* l; initialises a pointer to an address in memory - it does not allocate the memory for TList itself, so l most likely points to some random chunk of memory that you should not have access to.
You'd have to either call
l = malloc(sizeof(*l))
to reserve memory. Remember to call free(l); once you're done.
Alternatively declare l not as pointer, but rather as TList:
TList l;
[...]
TList_Init(&l);
This reserves memory in stack for TList, and passes a pointer via & to the method, with the proper memory allocated - in this case, you do not need to free the memory, as it's automagically freed once the method in which the variable was declared returns.
You never initialize the pointer l before you pass it to TList_Init(l);. Then assigning to l->n leads to undefined behavior in C language standardese because you use an indeterminate value.
What about making TList_Init() returning a ptr-to-TList instead?
TList *TList_Init (void)
{
TList *l;
l = malloc (sizeof *l);
/* Check l != NULL here ... omitted. */
printf("2test\n");
l->n = 0;
printf("3test\n");
l->tam = 100;
printf("4test\n");
l->v = malloc(sizeof(TItem) * l->tam);
printf("5test\n");
return l;
}

Hash Tables program crashes

I wonder if I'm doing something wrong in my program.
I manage to create a HashTable but when I send it through parameter to my displayingList() function, it crashes.
source.c (contains my functions):
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#include <math.h>
#include "header.h"
#define MAX 255
int countLetters(char myStr[])
{
int myLen = strlen(myStr), i;
int wordLen = 0;
for (i = 0 ; i < myLen; ++i)
{
wordLen += (int)(myStr[i]);
}
return (wordLen%256);
}
void populateList(NodeT *T[255], char myStr[])
{
NodeT *p, *q;
p = (NodeT *)malloc(sizeof(NodeT));
strcpy (p->key, myStr);
int myPos = countLetters(myStr);
if(T[myPos] == NULL)
{
p->next = NULL;
T[myPos] = p;
}
else
{
q = T[myPos];
p->next = q;
T[myPos] = p;
}
}
void displayList(NodeT *T[255])
{
int i;
NodeT *p;
for(i = 0 ; i < 255; ++i)
{
if(T[i] != NULL)
{
printf("Index: %d - Data:", i);
p = T[i];
while(p != 0)
{
printf("%s, ", p->key); // HERE IT CRASHES.
p = p->next;
}
printf("\n");
}
}
}
main.c (contains the int main()):
#include <stdio.h>
#include <stdlib.h>
#include "header.h"
int main(void)
{
NodeT *T[255];
int n, i;
printf("Give no. of elements:");
scanf("%d", &n);
fflush(stdin);
for(i = 0 ; i < n ; ++i)
{
char name[100];
gets(name);
populateList(T, name);
}
displayList(T);
return 0;
}
header.h (and my header):
#ifndef HEADER_H
#define HEADER_H
typedef struct cell
{
char key[100];
struct cell *next;
}NodeT;
int countLetters(char myStr[]);
void populateList(NodeT *T[], char myStr[]);
void displayList(NodeT *T[]);
#endif // HEADER_H
I tried to see what exactly happens with debugger and it seems that when I send T[] list to displayList() function, actually it doesn't have the same structure as it has in main.c.
ISSUE: the insertion works fine, but when I try to display my list (on each index) it crashes.
Any ideas?
Thanks in advance.
The possible solution is to declare the NodeT *T[255] global. However it isn't the best practice at all.

Resources