this is my 1.c content
#include "2.h"
#include<stdio.h>
#include<string.h>
void push(int ele)
{
stack[tos]=ele;
tos++;
}
char pop()
{
tos--;
return(stack[tos]);
}
void show()
{
int x=tos;
printf("--The Stack elements are.....");
while(x!=0)
printf("%c, ",stack[--x]);
}
//Function to get the precedence of an operator
int prec(char symbol)
{
if(symbol== '(')
return 0;
if(symbol== ')')
return 0;
if(symbol=='+' || symbol=='-')
return 1;
if(symbol=='*' || symbol=='/')
return 2;
if(symbol=='^')
return 3;
return 0;
}
and this is my 2.h content
#define size 10
char stack[size];
int tos=0,ele;
void push();
char pop();
void show();
int isempty();
int isfull();
char infix[30], output[30];
int prec(char);
and my main.c content is
#include "2.h"
#include<stdio.h>
#include<string.h>
int main()
{
int i=0,j=0,k=0,length;
char temp;
printf("\nEnter an infix expression:");
scanf("%s",infix);
printf("\nThe infix expresson is %s",infix);
length=strlen(infix);
for(i=0;i<length;i++)
{
//Numbers are added to the out put QUE
if(infix[i]!='+' && infix[i]!='-' && infix[i]!='*' && infix[i]!='/' &&
infix[i]!='^' && infix[i]!=')' && infix[i]!='(' )
{
output[j++]=infix[i];
printf("\nThe element added to Q is:%c",infix[i]);
}
//If an operator or a bracket is encountered...
else
{
if(tos==0) //If there are no elements in the stack, the operator is added to it
{
push(infix[i]);
printf("\nThe pushed element is:%c",infix[i]);
}
else
{
//Operators or pushed or poped based on the order of precedence
if(infix[i]!=')' && infix[i]!='(')
{
if(prec(infix[i]) <= prec(stack[tos-1]))
{
temp=pop();
printf("\n the poped element is :%c",temp);
output[j++]=temp;
push(infix[i]);
printf("\n The pushed element is :%c",infix[i]);
show();
}
else
{
push(infix[i]);
printf("\nThe pushed element is:%c",infix[i]);
show();
}
}
else
{
if(infix[i]=='(')
{
push(infix[i]);
printf("\nThe pushed-- element is:%c",infix[i]);
}
if(infix[i]==')')
{
temp=pop();
while(temp!='(')
{
output[j++]=temp;
printf("\nThe element added to Q is:%c",temp);
//temp=pop();
printf("\n the poped element is :%c",temp);
temp=pop();
}
}
}
}
}
printf("\nthe infix expression is: %s",output);
}
while(tos!=0)
{
output[j++]=pop();
}
printf("the infix expression is: %s\n",output);
}
i am doing this using MAKE in linux
the code is
myapp: main.o 1.o
gcc -o myapp main.c 1.c
main.o: main.c 2.h
gcc -c main.c
1.o: 1.c 2.h
gcc -c 1.c
but iin coming the error coming
gcc -o myapp main.c 1.c
/tmp/ccy0qyI1.o:(.bss+0x0): multiple definition of `tos'
/tmp/ccQZzbOI.o:(.bss+0x0): first defined here
collect2: ld returned 1 exit status
make: *** [myapp] Error 1
i m trying to fix it up. but not able to resolve
You are defining a global variable tos in a header file, which you include both from 1.c and main.c. So you end up with two global variables with the same name. The linker does not like that. As a traditional-unix extension, the linker may cope with such a situation if the multiply-defined variable is not explicitly initialized, but your code initializes the variable.
I recommend reading the K&R book which you will find in any decent university library.
#Thomas gave you a good explanation of your problem. The global variable tos declaration is in the header file 2.h which is included twice via #include in 1.c and main.c.
If you want to share the variable tos you should declaration it in 1.c or main.c, and modify 2.h to declare it as an extern, e.g.:
1.c:
int tos = 0;
2.h:
extern int tos;
Then you can access tos from main.c, but the variable is only defined once.
Sidebar: Just a suggestion for your own benefit, and for the benefit of sharing future questions in StackOverflow, try to minimize the source code, to the bare necessaries of generating the error. To the point where the program is trivial, because then the bug will be easier to isolate (for you and everyone else), and clearer for the reader, what they should focus on. As well, #Thomas suggestion of The C Programming Language is strongly encouraged as an excellent recommendation for any C programmer.
Related
i have recently started using threads ,so pretty new to this stuff. please no hate .i was working on a program which would calculate prime numbers till a limit N provided through the command line.
i would distribute this N to num_threads i.e. 4 .lets say the number is 40 and num_threads=4 then each thread should get 10 indexes.i created a structure containing the upper and lower limits for each thread.i passed a pointer of this structure and used the "high" and "low" attributes of this structure to control the flow.
there seems to be some kind of problem.if anyone of you can point out the mistake or tell me if this is the right thing to do i would be pretty grateful :)
geany gives the the following errors:
g++ -Wall -o "prime5000" "prime5000.cpp" (in directory: /home/jarrar/operating systems/threads)
/tmp/ccAHGsIw.o: In function `main':
prime5000.cpp:(.text+0xc9): undefined reference to `pthread_create'
prime5000.cpp:(.text+0xf6): undefined reference to `pthread_join'
collect2: error: ld returned 1 exit status
Compilation failed.
if executed from the terminal using the following command:
g++ prime5000.cpp -lpthread -o 5prime
./5prime
it will give :
Segmentation fault(Core dump)
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#define num_thread 4
void* calc(void* param);
struct fml
{
long low;
long high;
};
fml* x;
int main(int argc,char* argv[])
{
pthread_t threadArray[num_thread];
int thread;
for(thread=0;thread<num_thread;thread++)
{
x->low=thread*atoi(argv[1])/num_thread;
x->high=x->low+(thread+1)*atoi(argv[1])/num_thread;
pthread_create(&threadArray[thread],NULL,calc,&x);
}
int i;
for(i=0;i<num_thread;i++)
{
pthread_join(threadArray[i],NULL);
}
return 0;
}
void* calc(void* param)
{
fml* temp=(fml*)param;
long lowerLimit=temp->low;
long upperLimit=temp->high;
int i;
int j;
for(i=lowerLimit;i<upperLimit;i++)
{
for(j=2;j<i;j++)
{ if(i!=1||i!=0)
{
if(!(i%j==0))
{
printf("%d ",i);
}
}
}
}
pthread_exit(NULL);
}
As we all know, perf is the tool to get the CPU performance counter for a program, such as cache-miss, cache-reference, instruction executed etc.
Question :
How to get those performance counters for just a piece of code (such as a function) in one program in c or c++.
For example, my program firstly do some initializing, then do the work, then finalize, i just want to get the performance counter for the work, such as function do_something_1 .
int main(int argc, char ** argv) {
do_initialize();
for (int i = 0;i < 100 ;i ++) {
/* begin profile code */
do_something_1();
/* end profile code */
do_something_2();
}
do_finalize();
}
Finally, i found a library to get those counter for a piece of code.
PAPI
For example, if you want to measure L3 data cache read for some piece of code.
#include "papi.h"
#include <iostream>
#include <glog/logging.h>
#define ASIZE 2684354560
#define event_count (1) // the number of event you want to trace
int main(int argc, char ** argv) {
int events[event_count] = {PAPI_L3_DCR}; // L3 Data Cache Read
int ret;
long long int values[event_count]; // result
int* array = new int [ASIZE ];
/* start counters */
ret = PAPI_start_counters(events, event_count);
CHECK_EQ(ret, PAPI_OK);
size_t tot_cnt = 1;
for(size_t cnt = 0; cnt < tot_cnt; cnt ++) {
for(size_t i = 0;i < ASIZE ;i ++) {
array[i] = i;
}
}
/* read counters */
ret = PAPI_read_counters(values, event_count);
CHECK_EQ(ret, PAPI_OK);
for(size_t i = 0;i < event_count ;i ++) {
LOG(INFO) << " " << values[i];
}
return 0;
}
Makefile :
CXX?=g++
INC?=-I<path to where papi is installed>/include/
LIB?=-L<path to where papi is installed>/lib/ -lpapi -lglog
main : main.cpp
${CXX} -O3 ${INC} -o $# $< ${LIB}
all : main
.PHONY:
clean :
rm -f main
You can use operf (oprofile).
In short:
# Build you program with debugging information
# Start up the profiler
operf /path/to/mybinary
# generate a profile summary
opreport --symbols
# produce some annotated source
opannotate --source --output-dir=/path/to/annotated-source
Example annotated output:
$ opannotate --source --output-dir=/home/moz/src/annotated `which oprofiled`
$ vi /home/moz/src/annotated/home/moz/src/oprofile/daemon/opd_image.c # the annotated source output
...
:static uint64_t pop_buffer_value(struct transient * trans)
254 2.4909 :{ /* pop_buffer_value total: 2105 20.6433 */
: uint64_t val;
:
160 1.5691 : if (!trans->remaining) {
: fprintf(stderr, "BUG: popping empty buffer !\n");
: exit(EXIT_FAILURE);
: }
:
: val = get_buffer_value(trans->buffer, 0);
123 1.2062 : trans->remaining--;
65 0.6374 : trans->buffer += kernel_pointer_size;
: return val;
230 2.2556 :}
Examples
I did do some survey to solving the same problem in my project. I did find another framework called SkyPat (https://skypat.skymizer.com) which can get the PMU counters for a piece of code like PAPI.
I have tried both of PAPI and SkyPat to get the PMU counters for a function. I think the difference between of them is that SkyPat combines unit tests and perf_evnet. It refers the concept of Google Test and provides an interface to access PMU, so it’s easy to integrate with Google Test.
For example, if you want to measure cache references and cache for a function.
#include <unistd.h>
#include "pat/pat.h"
#include "test.h"
PAT_F(MyCase, my_test)
{
int result = 0;
COUNT(pat::CONTEXT_SWITCHES) {
test(10);
}
COUNT(pat::CPU_CLOCK) {
test(10);
}
COUNT(pat::TASK_CLOCK) {
test(10);
}
COUNT(pat::CACHE_REFERENCES) {
test(10);
}
COUNT(pat::CACHE_MISSES) {
test(10);
}
}
int main(int argc, char* argv[])
{
pat::Test::Initialize(&argc, argv);
pat::Test::RunAll();
}
And the result log of SkyPat.
[ pat ] Running 1 tests from 1 cases.
[----------] 1 test from MyCase.
[ RUN ] MyCase.my_test
[ TIME (ns)] 2537 1000 843 1855 1293
[EVENT TYPE] [CTX SWITCH] [CPU CLOCK] [TASK CLOCK] [CACHE REF] [CACHE MISS]
[RESULT NUM] 0 982 818 2 0
[==========] 1 test from 1 cases ran.
[ PASSED ] 1 test.
It sounds you look for profiling.
As you say you are under linux so have a look for gprof toolchain. Simply you have to compiler your prog with some compiler options and start your program. gprof after that inspect the generated profiling data and provide a result which contains information's for each code block.
First: Compile your prog with additional options:
g++ <source> -c -g -pg
...
Second: Link, you also need these options!
g++ <object1> <object2> ... <objectn> -g -pg -o <target>
Third: run your prog
./<target>
After that, get statistics:
gprof <target>
I am facing the same situation as yours and I did some study on this. Here is what I learned. Firstly, perf is included as a part of kernel and you could check its headers in
/usr/src/kernels/$VERSION/include/linux/perf_regs.h
/usr/src/kernels/$VERSION/include/linux/perf_event.h
/usr/src/kernels/$VERSION/include/uapi/linux/perf_event.h
And I think the core file is perf_event.h
You could also check its github website which has some clarification on how to use it. But it is not clear and now I still have many confusions.
In addition, I found a library very useful called pfmlib which is a helper library to program the perf events. It has examples and perf_examples for instructing how to do this in code-level. I am still working on it. Hope this help you. If you have some questions, we could study from each other.
The website of pfmlib is http://perfmon2.sourceforge.net.
I have the following sequence
executable (main) ---- (dlopen)---> libapp.so ---(dynamically linked)--> libfoo.so
libfoo.so in turn dynamically links to libfoo_strong.so. libfoo.so invokes a function from
libfoo_strong.so, but also has a weak definition (within foo.c which is compiled into libfoo.so).
Now, libapp.so invokes a function from libfoo.so (say invoke_foo_func_ptr() and this function >invokes a function pointer which stores the symbol that is defined as weak. My expectation is that >invokes_foo_func_ptr invokes the strong symbol, but it always goes to the weak symbol. Pls see the >code below for details.
PS: Dont ask me to explain the reason particular sequence of execution, but I am open to >workarounds.
foo_strong.c --> gcc -g -fPIC -shared -rdynamic foo_strong.o -o libfoo_strong.so
foo.c: --> gcc -g -fPIC -shared -rdynamic -L/users/ardesiga/cprogs/ld_r foo.o -o libfoo.so
app.c: --> gcc -g -fPIC -shared -rdynamic -L/users/ardesiga/cprogs/ld_r -lfoo -lfoo_strong app.o -o > libapp.so
/* foo_strong.c */
int
foo_weak_func (char *msg)
{
printf("[%s:%s] Reached strong, with msg: %s\n", __FILE__, __FUNCTION__, msg);
}
/* foo.c */
#include <stdio.h>
#include <stdlib.h>
#include "foo_ext.h"
#include "foo_weak.h"
int __attribute__ ((weak)) foo_weak_func (char *msg)
{
printf("[%s:%s], Reached weak, with msg: %s\n", __FILE__, __FUNCTION__, msg);
}
typedef int (*func_ptr_t) (char *msg);
func_ptr_t foo_func_ptr = foo_weak_func;
void
invoke_foo_func_ptr (char *msg)
{
printf("Inside %s\n", __FUNCTION__);
if (foo_func_ptr) {
(*foo_func_ptr)(msg);
} else {
printf("foo_func_ptr is NULL\n");
}
}
/* app.c */
#include "foo.h"
int
app_init_func (char *msg)
{
printf("Inside %s:%s\n", __FILE__, __FUNCTION__);
invoke_foo_func_ptr(msg);
}
/* main.c */
int main (int argc, char *argv[])
{
void *dl_handle;
char *lib_name;
app_init_func_t app_init_func;
if (!(argc > 1)) {
printf("Library is not supplied, loading libapp.so\n");
lib_name = strdup("libapp.so");
} else {
lib_name = strdup(argv[2]);
}
printf("Loading library: %s\n", lib_name);
dl_handle = dlopen(lib_name, RTLD_LAZY);
if (!dl_handle) {
printf("Failed to dlopen on %s, error: %s\n", lib_name, dlerror());
exit(1);
}
app_init_func = dlsym(dl_handle, "app_init_func");
if (app_init_func) {
(*app_init_func)("Called via dlsym");
} else {
printf("dlsym did not file app_init_func");
}
return (0);
}
My expectation is that invokes_foo_func_ptr invokes the strong symbol, but it always goes to the weak symbol.
Your expectation is incorrect and everything is working as designed.
Weak symbols lose to strong symbols when you link a single ELF binary. If you were to link a normal (strong) function foo and a weak foo into libfoo.so, the the strong definition would have won.
When you have multiple ELF images, some with strong foo, and some with weak foo, the first ELF image to define foo (regardless of whether weak or strong) wins. The loader will simply not look for any additional ELF images in its search scope once it finds the first image that does provide a definition for foo.
Dont ask me to explain the reason particular sequence of execution
That is quite an obnoxious thing to say.
I have a guess as to what your reason may be, and a solution for it, but you'll have to provide your reason first.
#include<stdio.h>
#include<math.h>
#include<pthread.h>
#include<stdlib.h>
long double x,fact[150],pwr[150],s[1];
int i,term;
void *Power(void *temp)
{
int k;
for(k=0;k<150;k++)
{
pwr[k] = pow(x,k);
//printf("%.2Lf\n",pwr[k]);
}
return pwr;
}
void *Fact(void *temp)
{
long double f;
int j;
fact[0] = 1.0;
for(term=1;term<150;term++)
{
f = 1.0;
for(j=term;j>0;j--)
f = f * j;
fact[term] = f;
//printf("%.2Lf\n",fact[term]);
}
return fact;
}
void *Exp(void *temp)
{
int t;
s[0] = 0;
for(t=0;t<150;t++)
s[0] = s[0] + (pwr[t] / fact[t]);
return s;
}
int main(void)
{
pthread_t thread1,thread2,thread3;
printf("Enter the value of x (between 0 to 100) (for calculating exp(x)) : ");
scanf("%Lf",&x);
printf("\nThreads creating.....\n");
pthread_create(&thread1,NULL,Power,NULL); //calling power function
pthread_create(&thread2,NULL,Fact,NULL); //calling factorial function
printf("Threads created\n");
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
printf("Master thread and terminated threads are joining\n");
printf("Result collected in Master thread\n");
pthread_create(&thread3,NULL,Exp,NULL);
pthread_join(thread3,NULL);
printf("\nValue of exp(%.2Lf) is : %Lf\n\n",x,s[0]);
exit(1);
}
I was trying to run the above program in linux ubuntu. It is giving following errors
parallelcomp.cpp:(.text+0x1ec): undefined reference to `pthread_create'
parallelcomp.cpp:(.text+0x207): undefined reference to `pthread_create'
parallelcomp.cpp:(.text+0x222): undefined reference to `pthread_join'
parallelcomp.cpp:(.text+0x233): undefined reference to `pthread_join'
parallelcomp.cpp:(.text+0x262): undefined reference to `pthread_create'
parallelcomp.cpp:(.text+0x273): undefined reference to `pthread_join'
The error is mostprobably due to linking binary with pthreads.
Is there any command in ubuntu terminal whcih can solve this problem.?
I have tried with several commands given in this community forum, non of them is helpful.
Is there anyone who would like to help me?
I am also very new to Linux ubuntu.
Any kind of suggestion is appreciable.
How to include libpthread ?
When I am putting the following command, gcc -pthread -o term term.c, in terminalwe i get the following error: Command line option 'p' [from -pthread] is not known.
Please try the following -lpthread. Which version of gcc are you using?
Why do I get "undefined reference" errors even when I include the right header files?
While compiling add link to pthread library -lpthread
In a larger piece of code, I noticed that the g_atomic_* functions in glib were not doing what I expected, so I wrote this simple example:
#include <stdlib.h>
#include "glib.h"
#include "pthread.h"
#include "stdio.h"
void *set_foo(void *ptr) {
g_atomic_int_set(((int*)ptr), 42);
return NULL;
}
int main(void) {
int foo = 0;
pthread_t other;
if (pthread_create(&other, NULL, set_foo, &foo)== 0) {
pthread_join(other, NULL);
printf("Got %d\n", g_atomic_int_get(&foo));
} else {
printf("Thread did not run\n");
exit(1);
}
}
When I compile this with GCC's '-E' option (stop after pre-processing), I notice that the call to g_atomic_int_get(&foo) has become:
(*(&foo))
and g_atomic_int_set(((int*)ptr), 42) has become:
((void) (*(((int*)ptr)) = (42)))
Clearly I was expecting some atomic compare and swap operations, not just simple (thread-unsafe) assignments. What am I doing wrong?
For reference my compile command looks like this:
gcc -m64 -E -o foo.E `pkg-config --cflags glib-2.0` -O0 -g foo.c
The architecture you are on does not require a memory barrier for atomic integer set/get operations, so the transformation is valid.
Here's where it's defined: http://git.gnome.org/browse/glib/tree/glib/gatomic.h#n60
This is a good thing, because otherwise you'd need to lock a global mutex for every atomic operation.