C programming error - counter already defined? - c

ERRORS:
1) _counter already defined error
2) one or more multiply defined symbols found
structure.h:
extern int counter = 0;
List.c:
in one method i increment the counter.
++counter;
in another method i set the counter to a value within an object
llist->taskID = counter;
Messages.c:
use counter for while loop
while(counter < 1)
{
//do stuff
}
why does this error occur? I did a ctrl F and searched for all the instances i use counter... these are the only instances i use it...

Your header file structure.h should only have a declaration (not a definition), like:
extern int counter;
One (only) of the implementation files, conventionally the *.c file containing main, should have a definition like
int counter = 0;

Related

Can gcc/clang optimize initialization computing?

I recently wrote a parser generator tool that takes a BNF grammar (as a string) and a set of actions (as a function pointer array) and output a parser (= a state automaton, allocated on the heap). I then use another function to use that parser on my input data and generates a abstract syntax tree.
In the initial parser generation, there is quite a lot of steps, and i was wondering if gcc or clang are able to optimize this, given constant inputs to the parser generation function (and never using the pointers values, only dereferencing them) ? Is is possible to run the function at compile time, and embed the result (aka, the allocated memory) in the executable ?
(obviously, that would be using link time optimization, since the compiler would need to be able to check that the whole function does indeed have the same result with the same parameters)
What you could do in this case is have code that generates code.
Have your initial parser generator as a separate piece of code that runs independently. The output of this code would be a header file containing a set of variable definitions initialized to the proper values. You then use this file in your main code.
As an example, suppose you have a program that needs to know the number of bits that are set in a given byte. You could do this manually whenever you need:
int count_bits(uint8_t b)
{
int count = 0;
while (b) {
count += b & 1;
b >>= 1;
}
return count;
}
Or you can generate the table in a separate program:
int main()
{
FILE *header = fopen("bitcount.h", "w");
if (!header) {
perror("fopen failed");
exit(1);
}
fprintf(header, "int bit_counts[256] = {\n");
int count;
unsigned v;
for (v=0,count=0; v<256; v++) {
uint8_t b = v;
while (b) {
count += b & 1;
b >>= 1;
}
fprintf(header, " %d,\n" count);
}
fprintf(header, "};\n");
fclose(header);
return 0;
}
This create a file called bitcount.h that looks like this:
int bit_counts[256] = {
0,
1,
1,
2,
...
7,
};
That you can include in your "real" code.

Counting the number of function calls in an executable

I am trying to find the exact number of function calls to one of my implemented C function inside my code. The project includes several C files. What is the easiest solution to figure out how many times a function is called during the execution of the program? Specifically, I am interested to know how many times a specific function calls another function. For instance I have a C file like:
//file1.c
int main(){
foo1();
return 0;
}
and other C files like:
//file2.c
void foo1(){
foo2();
...
foo2();
}
and
//file3.c
void foo2(){
foo3();
foo3();
foo3();
}
Now I have my final executable a.out and want to know how many times foo3() is called inside foo1().
BTW, I am compiling and running my project on Linux.
You can use 2 global variables (put extern at the places that access the variable outside the file you declare them) :
int foo1_active = 0;
int foo3_counter = 0;
then each time foo1 is called you increment it variable and before the return you decrement it:
void foo1() {
foo1_active++;
...
foo1_active--;
return
}
when foo3 is called you check if foo1 active and if it does you increment the counter:
void foo3() {
if foo1_active > 0 {
foo3_counter++;
}
...
}
You have an ubuntu flag, so I assume you are using gcc. I'd strongly consider adding -pg to your CFLAGS and trying out gprof.
Profiling works by changing how every function in your program is
compiled so that when it is called, it will stash away some
information about where it was called from. From this, the profiler
can figure out what function called it, and can count how many times
it was called. This change is made by the compiler when your program
is compiled with the `-pg' option, which causes every function to call
mcount (or _mcount, or __mcount, depending on the OS and compiler) as
one of its first operations.
You can count function calls using a static variable instead of global variable.
int inc(){
static int counter = 1;
counter++;
return counter;
}
int main(){
int i;
for (i = 0; i < 10; i++)
printf("%d\n", inc());
return 0;
}

C macro expansion of a function pointer based on for loop incrementor

I have a function that takes a pointer to a function as a parameter.
This function get's called within a for loop due to the similar nature of the names of the function pointer I use a macro to expand the name into the function. IT looks something like this:
void fill(int, int(*funcbase)(int));
int funcbase0(int);
int funcbase1(int);
int funcbase2(int);
int funcbase3(int);
/// all the way through funcbase31
#define FILL_(num) fill(num, funcbase##num)
#define FILL(num) FILL_(num)
for(int i = 0; i < 32; i++)
FILL(i);
I would like this to call fill for 0,1,2,... and funcbase0, funcbase1, funcbase2,... , but it calls fill with the second parameter of "funcbasei" It does not expand i every time.
Is what I'm trying to do possible? What compiler would I need to try? (I'm using gcc 4.9.3)
What you are trying to do is not possible with a macro because macros are expanded at compile time, well before the runtime and loops start running.
However, you can easily do this with a for loop on an array of function pointers:
typedef int(*funcbase_t)(int);
funcbase_t fbases[] = {
funcbase0, funcbase1, funcbase2, funcbase3, ...
};
Now you can run your loop on fbase array:
for(int i = 0; i < 32; i++)
fbases[i](i);
You can use the preprocessor to do this, by recursively splitting the interval into parts and calling it for each one. Or use the pre-built version in boost:
#include <boost/preprocessor/repetition/repeat.hpp>
// and in code
#define FILL_(num) fill(num, funcbase##num)
#define FILL(num) FILL_(num)
#define MACRO(z, n, text) FILL_(n);
BOOST_PP_REPEAT(4, MACRO, 0);

How does this C code (from lua library, Torch) even compile/work?

See https://github.com/torch/nn/blob/master/generic/Tanh.c
For example,
static int nn_(Tanh_updateOutput)(lua_State *L)
{
THTensor *input = luaT_checkudata(L, 2, torch_Tensor);
THTensor *output = luaT_getfieldcheckudata(L, 1, "output", torch_Tensor);
THTensor_(resizeAs)(output, input);
if (input->nDimension == 1 || !THTensor_(isContiguous)(input) || !THTensor_(isContiguous)(output))
{
TH_TENSOR_APPLY2(real, output, real, input, \
*output_data = tanh(*input_data););
}
else
{
real* ptr_output = THTensor_(data)(output);
real* ptr_input = THTensor_(data)(input);
long i;
#pragma omp parallel for private(i)
for(i = 0; i < THTensor_(nElement)(input); i++)
ptr_output[i] = tanh(ptr_input[i]);
}
return 1;
}
First, it I don't know how to interpret the first line:
static int nn_(Tanh_updateOutput)(lua_State *L)
What are the arguments here? What does Tanh_updateOutput refer to? Does "nn_" have special meaning?
Second, "TH_TENSOR_APPLY2" and "THTensor_(...)" are both used but I don't see where they are defined? There are no other includes in this file?
nn_ is a macro. You can find the definition by searching the repository for "#define nn_"; it's in init.c:
#define nn_(NAME) TH_CONCAT_3(nn_, Real, NAME)
You can keep following the chain of macro definitions, and you'll probably end up with some token pasting thing that makes nn_(Tanh_updateOutput) expand to the name of the function.
(It's weird that generic/Tanh.c doesn't have any includes; generic/Tanh.c must be included by some other file. That's unusual for .c files.)

Using array in .h file

I am trying to learn to program in C (not C++!). I've read about external variables, which should (according to the writer) give a nicer code. In order to use the external variables, I must #define them in the .h file, before I can use them in main.c file, using the extern command in front of the variable. I am trying to create an array in the .h file like this:
#define timeVals[4][2];
timeVals[0][0] = 7;
timeVals[0][1] = 45;
timeVals[1][0] = 8;
timeVals[1][1] = 15;
timeVals[2][0] = 9;
timeVals[2][1] = 30;
timeVals[3][0] = 10;
timeVals[3][1] = 25;
(it's a clock I'm trying to make, simple program in console). The first column indicates hours and the second indicates minutes. In my main I have written
extern int timeVals[][];
but I get an error telling me that " expected identifier or '(' before '[' token|" and I can't see what the issue is... any ideas or advices?
I am using the .h file to learn how to use external variables, so I can't move the values back into main.c
First, this:
#define timeVals[4][2];
Is a confusion. You mean this:
int timeVals[4][2];
Put that in your .h file, then in your .c file, something like this:
int timeVals[4][2] = {
{ 1, 2 }, // ...
};
That's how you initialize the entire array (any unspecified elements will be zero).

Resources