Why all these errors when building this C project? - c

I'm coding some similar programs in C as part of an XCode project. As this new program needs to exhibit some slightly different functionality to what the 1st working iteration was, I thought targets were the best thing to use.
So I tried to create a new target, and did it the way I thought was the right way from googling how to (in XCode). But on compilation, I get way too many errors.
Here is a screen of the errors I get:
I see that it's having a problem with loads of different characters, so I'm sure it's probably a simple problem like some missing files. But I didn't know what to Google so I hope it's okay that I'm asking.
On a related note, does anyone know why my first version of the program, called main.c, didn't need to include a header file like the one above did?
Thanks!
EDIT:
Here's the code from the new target, which is practically identical to the so far unchanged first version of the program:
/*
* ScalarProduct.c
* Concurrency_Practical1
*
* Created by Chucky on 11/03/2012.
* Copyright 2012 __MyCompanyName__. All rights reserved.
*
*/
#include "ScalarProduct.h"
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
//the final answer
int finalScalarProd;
//random variable
int rand_seed=10;
int rand()
{
int n;
n = random()%11;
//printf("%d\n", n);
return(n);
}
void* getScalarProduct(void *arg)
{
//index for loop
int i;
//scalarProduct of 10 integers
int * scalarProd = (int *) arg;
//my two arrays
int list1[10];
int list2[10];
for (i=0; i<10; i++) {
list1[i] = rand();
list2[i] = rand();
*scalarProd += list1[i]*list2[i];
printf("%d:\t\t %d\t\t %d\t\t %d\t\t\n", i, list1[i], list2[i], list1[i]*list2[i]);
}
return((void*)scalarProd);
}
int main (int argc, const char * argv[]) {
// insert code here...
pthread_t t1, t2;
int sp1= 0, sp2 = 0;
printf("Index\t List1\t List2\t Product\n\n");
pthread_create( &t1, NULL, getScalarProduct, &sp1);
pthread_create( &t2, NULL, getScalarProduct, &sp2);
pthread_join( t1, NULL);
pthread_join( t2, NULL);
printf("\nScalar Products: %d %d\n", sp1, sp2);
finalScalarProd = sp1 + sp2;
printf("Result: %d\n", finalScalarProd);
return 0;
}

From the errors, it almost looks as if you are mixing Objective-C headers and compiling with the C compiler. It's still hard to tell though.

Your project is including/importing the AppKit-Header, which is ObjectiveC and not pure C.
As your quoted source does not mention it, I would bet that it is imported within the precompiled header. Check your project's precompiled header for such entry/ies. It will be named just like your project, with the extension .pch. You may want to remove any ObjectiveC imports.
Also check if you used any ObjectiveC frameworks in your project. When in doubt, remove all listed frameworks from your project.

Related

Starting the debuggee failed: No executable specified, use `target exec'

Code:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
// to generate numbers
void gen_data(int b[], int n)
{
int i;
for (i = 0; i < n; i++)
b[i] = rand() % 101;
}
// to display numbers
void disp_data(int b[], int n)
{
int i;
for (i = 0; i < n; i++)
printf("%d \n", b[i]);
}
// insert at desired posn
void insert(int b[], int n, int elt, int pos)
{
int i;
for (i = n - 1; i >= pos; i--)
b[i + 1] = b[i];
b[pos] = elt;
}
// delete an elt at given position
void delete (int b[], int n, int pos)
{
int i;
for (i = pos + 1; i < n; i++)
b[i - 1] = b[i];
}
// driver code
int main()
{
int a[100], pos, n = 10, let;
int opt;
system("cls");
gen_data(a, n);
while (1)
{
printf("\n 1- Insert 2-Delete 3-Display 4-quit\n");
scanf("%d %d", &pos, &elt);
insert(a, n, elt, pos);
n++;
break;
case 2:
printf("enter position at which elt to be deleted: ");
scanf("%d", &pos);
delete (a, n, pos);
n--;
break;
case 3:
printf("the numbers are : \n");
disp_data(a, n);
break;
}
if (opt == 4)
break;
} // end while
}
Log:
Active debugger config: GDB/CDB debugger:Default
Building to ensure sources are up-to-date
Selecting target:
Debug
Adding source dir: C:\Users\Ranju\Desktop\you\lab pro\
Adding source dir: C:\Users\Ranju\Desktop\you\lab pro\
Adding file: C:\Users\Ranju\Desktop\you\lab pro\bin\Debug\lab pro.exe
Changing directory to: "C:/Users/Ranju/Desktop/you/lab pro/."
Set variable: PATH=.;C:\MinGW\bin;C:\MinGW;C:\Windows\System32;C:\Windows;C:\Windows\System32\wbem;C:\Windows\System32\WindowsPowerShell\v1.0;C:\Windows\System32\OpenSSH;C;C:\Users\Ranju\AppData\Local\Microsoft\WindowsApps;C:\Program Files\CodeBlocks\MinGW\bin
Starting debugger: C:\Program Files\CodeBlocks\MINGW\bin\gdb.exe -nx -fullname -quiet -args "C:/Users/Ranju/Desktop/you/lab pro/bin/Debug/lab pro.exe"
done
Setting breakpoints
Debugger name and version: GNU gdb (GDB) 8.1
Starting the debuggee failed: No executable specified, use `target exec'.
Debugger finished with status 0
In my case, removing space(s) from the project path resolved the problem. Maybe you should try to change path like this:
"C:/Users/Ranju/Desktop/you/labpro/bin/Debug/lab pro.exe"
I recently had the same issue when starting to use CodeBlocks on Windows10 (C::B version 20.03 in my case). The problem was that I also had MinGW installed long before I installed CodeBlocks and CodeBlocks took the gdb.exe from that path instead of taking it from the MinGW path that was installed within CodeBlocks.
The solution for me was to change the default executable path in Settings -> Debugger... -> GDB/CDB debugger -> Default to the gdb.exe that was installed when I installed CodeBlocks. So: <C::B_installation_path>\MinGW\bin\gdb.exe.
After that change, the problem was solved.
I don't know how relevant this may be, but I seem to have the same or similar problem. See the material at
How do you debug using 'Code::Blocks 20.03' (the "mingw" version)?
especially that after the sentence, I have hopefully made progress towards an answer..
I have now added a proper answer to the above question..
I asume that you have MinGW installed, in the directory C:\MinGW.
Perhaps, AT YOUR OWN RISK, you could try temporarily renaming the folder C:\MinGW to something else, and try running the debugger.
I had MinGW pre-installed, when I installed Code::Blocks 20.03 using codeblocks-20.03mingw-setup.exe ( the 8th April 2021 version , default installation accepted). I also had a problem debugging. There is now a fix for this, which seems quite general, applying even without a pre-installed MinGW, see the answer to the other question ( link provided above ).
The fix involves changing a debugger setting, but in your case, you seem to be trying to use the correct debugger, see the line that you give, which is shown just below
Starting debugger: C:\Program Files\CodeBlocks\MINGW\bin\gdb.exe -nx -fullname -quiet -args "C:/Users/Ranju/Desktop/you/lab pro/bin/Debug/lab pro.exe"
In the above, you appear to be trying to use a debugger, from the directory, C:\Program Files\Codeblocks\MinGW\bin, which seems O.K., rather than one from C:\MinGW\bin, which is where the debugger was, that I was trying to use, see the other question.
However, you may be using something other than the debugger from the directory C:\MinGW.
Whether or not you have MinGW installed in C:\MinGW, you may need to alter some Setting in Code::Blocks.
I also had this problem. I am currently running Code::Blocks 17.12 on Windows 10. In my case, I simply upgraded my compiler to Mingw64 bit. To fix: I changed an entry in the default.conf file located in c:\users\logonname\appdata\roaming\codeblocks
directory. After making a copy of the original file I changed the line corresponding to the old debugger, gdb32.exe to the new file gdb.exe in its new directory. That fixed the problem. This was the default.conf old line, before making my change: <![CDATA[C:\Program Files (x86)\CodeBlocks\MinGW\bin\gdb32.exe]]>.

C is there a workaround to allow dynamic function calls?

I have read that C does not support dynamic function calls. My program has an ever growing number of test cases implemented as separate functions like -
int testcase1(void);
int testcase2(void);
int testcase3(void);
Each time I add a new test case, I also have have to add the call to my main function like -
int main(int argc, char **argv){
assert(!testcase1());
assert(!testcase2());
assert(!testcase3());
}
I would prefer to call something like assert(!testcase*()) where * matches any string which resolves to a valid function name in my program.
Can you think of a more convenient solution?
If you all your testcases have same signature then you can use an array of function pointers:
void (*func[])() = { testcase1, testcase2 };
for (size_t i = 0; i < sizeof(func)/sizeof(func[0]); i++) {
assert(!func[i]());
}
The best solution is likely to write a few extra lines of code when you add new test cases - it really isn't a big issue. I would recommend something along the lines of the function pointer array, as suggested in another answer.
However, just to show that everything is possible in C if you throw ugly macros at the problem, here is a not recommended alternative:
#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
#define TEST_CASES \ // list of "x macros"
X(testcase1) \
X(testcase2) \
X(testcase3)
#define X(func) bool func (void); // declare function prototypes
TEST_CASES
#undef X
bool (*const test_cases[])(void) = // array of read-only function pointers
{
#define X(func) &func, // point at each function
TEST_CASES
#undef X
};
int main (void)
{
for(size_t i=0; i<sizeof(test_cases)/sizeof(test_cases[0]); i++)
{
assert(test_cases[i]());
}
}
bool testcase1 (void) { puts(__func__); return true; }
bool testcase2 (void) { puts(__func__); return true; }
bool testcase3 (void) { puts(__func__); return false; }
Output:
testcase1
testcase2
testcase3
Assertion failed!
For each new test case, you would only have to write a function definition and then add it to the "x macro" list TEST_CASES. However, you need very good reasons to introduce ugly tricks like these in production code!
You can use function pointers. Read also about closures (but C99 or C11 don't have them) and callbacks.
Many operating systems provide dynamic loading. On POSIX operating systems (such as Linux or MacOSX) you can get a function pointer (actually an address) from its name in some library (or in the program executable) using dlopen & dlsym. Other operating systems may provide similar functionalities.
At last, you should consider having your testing main function be generated by some script (or some program emitting C code), using metaprogramming techniques. So you would write something which generates the C code of your testing main having a long sequence of assert, and improve your build procedure (e.g. your Makefile if using make) to run appropriately that specialized C code generator. Details are of course specific to your code. You might add some conventions (e.g. add some special comment to be parsed by your test generator, etc...).
I decided to follow #Nominal Animal and #Basile Starynkevitch's approach. In mymainprog.c, I added -
int runtests(void){
void *testh;
int (*testp)(void);
char *dlmsg;
int rc;
char funcname[8];
int testnum;
testh = dlopen("libsmtests.so", RTLD_LAZY);
if (!testh){
printf("%s\n", dlerror());
return 1;
}
dlerror();
for (testnum =1; testnum < 1000; testnum++){
sprintf(funcname,"testcase%d", testnum);
*(void **) (&testp) = dlsym(testh, funcname);
dlmsg = dlerror();
if (dlmsg == NULL) {
rc = (*testp)();
printf("%s called, rc=%d\n", funcname, rc);
}
}
dlclose(testh);
return 0;
}
I add my testcases to a separate file (testcases.c) like this -
int testcase1(void){
return [some testcase expression]
}
int testcase2(void){
return [another testcase expression]
}
and then compile it as a shared library with position-independant code (-fPIC) to libsmtests.so. The advantage is slightly less typing since I don't need to code a call to testNNNN() after adding the implementation of a new functionint testcaseNNN(void) to testcases.c

Use a dynamic library dll in C program

I want to use a dll-file in my C-Code, but are very confused about the syntax.
My Story: I made a simple function in Matlab ( f(x1,x2)=x1*x2 ), with the "Matlab Coder" I translated it to C-Code and generated an exe, I could run it from the terminal with arguments.Now I generated a dll instead of an exe and want to use the dll.
Since now I could not make Code explanations, I googled, make work for me. I look up Syntax in http://en.cppreference.com/w/ but for my surprise there wasn't even an entry for e.g. GetProcAddress or LoadLirbary.
Here is the C-Code in which I would like to use the dll:
#include <stdio.h>
#include <stdlib.h>
/*
* In my dream I would load the dll function here
* with something like Load(mytimes4.dll)
*/
int main(int argc, char *argv[]) {
double x1,x2,myresult;
//Load Arguments from Terminal
sscanf(argv[1], "%lf", &x1);
sscanf(argv[2], "%lf", &x2);
// Use and print the function from mytimes4.dll
myresult = mytimes4(x1,x2);
printf("%3.2f\n",myresult);
return 0;
}
After generating the dll, Matlab gave me the following folder:
"dll-folder" produced by Matlab
Can someone give me a most simple but complete Code that would work with my example? What files are needed (maybe .def or .exp)? Also for Explanations of the lines involved using the dll I would be gratefull. Or if not, you maybe have some background knowledge that makes the complex syntax reasonable.Thanks in advance!
System information: Windows 7 Pro 64, Matlab 64 2016b, gcc cygwin 64, eclipse ide.
With the link of thurizas I could solve my problem.
https://msdn.microsoft.com/en-us/library/windows/desktop/ms686944(v=vs.85).aspx
I copied the code from the side. Below you can see the code with additional comments of mine and with ,in my opinion, more clearly naming. Thus it is probably easier to use for beginners as I am.
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
/*Declaration of the function,contained in dll, as pointer with the arbitrary pointer name
"*MYFUNCTIONPOINTER" (not sure if it has to be in big letters).
In my case the function means simply f(x1,x2) = x1*x2 and is thus as double declared*/
typedef double (*MYFUNCTIONPOINTER)(double, double);
int main() {
HINSTANCE hinstLib;
//"myfunction" is the arbitrary name the function will be called later
MYFUNCTIONPOINTER myfunction;
BOOL fFreeResult, fRunTimeLinkSuccess = FALSE;
//Tell the dll file
hinstLib = LoadLibrary(TEXT("mypersonal.dll"));
if (hinstLib != NULL)
{
/* At this line "myfunction" gets its definition from "MYFUNCTIONPOINTER"
and can be used as any other function.The relevant function in the dll has
to be told here.*/
myfunction = (MYFUNCTIONPOINTER) GetProcAddress(hinstLib, "mydllfunction");
// If the function address is valid, call the function.
if (NULL != myfunction)
{
fRunTimeLinkSuccess = TRUE;
// The function can be used.
double myoutput;
myoutput = myfunction(5,7);
printf("%f\n",myoutput);
getchar();
}
// Free the DLL module.
fFreeResult = FreeLibrary(hinstLib);
}
// If unable to call the DLL function, use an alternative.
if (! fRunTimeLinkSuccess)
printf("Message printed from executable\n");
return 0;
}

Selecting a random thread in c

I need to randomly select two out of three threads, and I've come up with a few ideas but I'm not sure if they would work.
Is it better to have an array of 3 threads and then have another thread choose from there, or to have three independent threads? And in both cases, how would you even write the function that would randomly select them? From what I understand, rand() can't be used because it's only for integers, and other than that I have no clue what to use.
This is kind of a game project, and the winner of the two selected threads plays with the remaining thread. Can the same function be used for both instances then, or does there have to be a new one? I'm guessing the most useful thing would be the same thread using the same function, only with its choices narrowed down?
I know this is probably simple but I'm only just starting out with threads, so excuse my poor skills. Any help is greatly appreciated!
EDIT: Thank you everyone! However, since I'm already confused I really don't want to go into semaphores now. I've written some code based on one of the comments but it's not giving me the wanted output. Here's what I have:
EDIT #2: I somehow managed to write it! The only thing left is for the function to call itself again but the pointers kind of confuse me so I don't know how to call it in the else part, and I don't know how else to stop the randomized values from repeating.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *play (void *myvar);
void *select (void *var);
pthread_t tid[3], th;
int i, ra1, ra2;
int main(int argc, char *argv[]) {
pthread_create(&th, NULL, &select, NULL);
for (i = 0; i < 3; i++) {
pthread_create(&tid[i], NULL, &play, NULL);
}
pthread_join(th, NULL);
for (i = 0; i < 3; i++) {
pthread_join(tid[i], NULL);
}
return 0;
}
void *play (void *myvar) {
printf("Thread%i hits the ball!\n", i);
return NULL;
}
void *select (void *var) {
srand ( time(NULL) );
ra1 = rand() % 3 + 1;
ra2 = rand() % 3 + 1;
if (ra1 != ra2) {
printf("Threads have been chosen! Thread%i and Thread%i will start the game!\n",
ra1, ra2);
}
else //what to do?;
return NULL;
}
I'm assuming that you want 2 of 3 threads to perform some task, and that this selection should be random. I further assume that you want these 3 threads to do the selection "in common", i.e. not requiring a forth thread to do the selection (or to have one of the three doing a special selection procedure).
A possible approach would be to use a counting semaphore to "protect" the task and only allow 2 threads to use it, i.e. initialize the semaphore to 2. You can then have each thread sleep a random (small) delay, and try to acquire the semaphore.
Without much comment, see this example:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
struct data {
sem_t * semaphore;
int random;
char const * name;
};
void task(char const * name) {
printf("WOOOOO %s\n", name);
}
void * operation(void * d) {
struct data * data = d;
usleep(data->random % 1000);
if (sem_trywait(data->semaphore) == 0) {
task(data->name);
} else {
printf("FAILED, such a shame for %s\n", data->name);;
}
return NULL;
}
int main(void) { // NOTE: Demo, thus no error checking
srand(time(NULL));
sem_t * semaphore = malloc(sizeof(*semaphore));
struct data data[3] = {
{semaphore, rand(), "John"},
{semaphore, rand(), "Marry"},
{semaphore, rand(), "Rupert"}
};
pthread_t others[2];
sem_init(semaphore, 0, 2);
pthread_create(&(others[0]), NULL, &operation, &(data[0]));
pthread_create(&(others[1]), NULL, &operation, &(data[1]));
(void)operation(&(data[2]));
pthread_join(others[0], NULL);
pthread_join(others[1], NULL);
sem_destroy(semaphore);
free(semaphore);
return 0;
}
(Live on ideone)
Note that using rand makes this choice here actually pseudo-random. Getting rid of the sleeping part can lead to a real random selection, especially when the threads have been doing different things previously. (Although I can imagine a situation where one would be able to influence the threads from the outside to achieve a particular selection)
Array of thread ID should server your purpose. Use the rand() function to randomly select the index of the array. Whatever thread ID is stored at that index of your array should be your selected thread.

Compiler doesn’t locate GCD header file on Windows

I need to use Grand Central Dispatch in my program but I don’t know how to use it on Windows.
The error I’m getting is
error: dispatch/dispatch.h: No such file or directory
#include <dispatch/dispatch.h>
int main (int argc, const char * argv[])
{
dispatch_group_t group;
dispatch_queue_t queue; // thread queues to use
group = dispatch_group_create();
queue= dispatch_queue_create("queue", NULL);
dispatch_sync(queue, ^{
puts("Dispatch test");
} );
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
dispatch_main();
return 0;
}
Portable libdispatch
[libdispatch-dev] Lion libdispatch sources posted & next steps for macosforge repo
You might be able to use GCD API (libdispatch) on Windows. However, for Blocks, Blocks supported compiler(gcc with Apple's patch or LLVM clang) is needed.

Resources