Share global variable between .c file - c

Hi I just wondering how to Share global variable between .c file.
I try to add follow code, but still get error.
test.c file
#include <stdio.h>
int max = 50;
int main()
{
printf("max %d", max); // result max 50
}
pass.h
extern int max;
passed.c
#include <stdio.h>
#include "pass.h"
max;
int main()
{
printf("pass %d \n", max);
return 0;
}
But when I compile passed.c I get follow error
Undefined symbols for architecture x86_64:
"_max", referenced from:
_main in passed-iOMugx.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Can anyone help? Thank you so much.

You can declare the variable in a header file, e.g. let's say in declareGlobal.h-
//declareGlobal.h
extern int max;
Then you should define the variable in one and only file, e.g. let's say, test.c. Remember to include the header file where the variable was declared, e.g. in this case, declareGlobal.c
//test.c
#include "declareGlobal.h"
int max = 50;
You can then use this variable in any file- just remember to include the header file where it's declared (i.e. declareGlobal.c), for example, if you want to use it in passed.c, you can do the following:
//passed.c
#include <stdio.h>
#include "declareGlobal.h"
#include "test.c"
int main()
{
printf("pass %d \n", max);
return 0;
}

The problem is that you have two programs, and data (like variables) can not be shared that simply between programs.
You might want to read about shared memory and other inter-process communication methods.
If on the other hand you only want to have one program, and use a variable defined in another file, you still are doing it wrong. You can only have one main function in a single program, so remove the main function from one of the source files. Also in pass.c the expression max; does nothing and you don't need it.
Then pass both files when compiling, like
$ clang -Wall -g test.c pass.c -o my_program
After the above command, you will (hopefully) have an executable program named my_program.

Related

Example of a translation unit vs file scope

Taking the following program as an example:
// myprogram.c
#include<stdio.h>
int a, b;
int main(void)
{
printf("A: %d\n", a);
printf("B: %d\n", b);
}
// friendsprogram.c
int a=1;
static int b=2;
$ gcc myprogram.c friendsprogram.c -o out; ./out
A: 1
B: 0
How would the translation units be classified in the above? And how what that be different than just the contents of the file "myprogram.c" and "friendsprogram.c"? Does the translation unit ever depend on the command that is issued to the compiler? For example, If I change the command to just:
$ gcc myprogram.c -o out; ./out
My output becomes:
A: 0
B: 0
A translation unit is a source file along with all of its included headers that is compiled as a single unit.
In this example, myprogram.c along with the header stdio.h is one translation unit. The file friendsprogram.c is another translation unit.
Note that this doesn't change when you compile like this:
gcc myprogram.c friendsprogram.c -o out
Because this command line combines compiling and linking into a single step. A temporary object file is created for myprogram.c and another for friendsprogram.c, then those object files are linked to create the file "out".
What's happening is a side effect of old lenient compiler/linker behavior and a so-called "common" section.
int a;
The C spec says this global-scope variable is initialized to zero. You would expect this to go into the .bss (zero-initialized data) section of the executable.
But in GCC <10, the variable is put into the "common" section when that file (translation unit) is compiled.
int a=1;
Now you've provided an initialization, and this variable will go into the .data section.
But when the linker links these two object files together, rather than issue a "multiple definitions" (for the same name) error, it will do something controversial, and merge them into one variable, due to the common section semantics.
By passing -fno-common, or using GCC >= 10, the common section is not used, and the linker will issue an error and refuse to link your program.
So what should you do? Simple: provide only one definition for any name.
If you really want to use global variables (undesirable in general), and you want to put them in a separate translation unit (weird), use extern in your other files:
data.h
// Declaration: Tells everyone that 'a' exists somewhere
extern int a;
data.c
#include "data.h"
// Definition: defines the variable and its initial value
int a = 42;
main.c
#include <stdio.h>
#include "data.h"
int main(void)
{
printf("a = %d\n", a);
}

Compiling C programs with static files

I am trying to compile a c program with a static library and its not working .
This is the error :
undefined reference to `calculatearea'
collect2.exe: error: ld returned 1 exit status .
The static files were made with the gcc / g++ compilers .
This is the main code :
#include <stdio.h>
#include <stdint.h>
int calculatearea(int a , int b);
int main()
{
int c = calculatearea(2,4);
printf("%d",c);
getchar();
return 0;
}
edit :
: screenshot of compiler error
From the above code we can see that you have declared the function int calculatearea(int a , int b); but have not written any definition for the same. and you are calling this function in the main. compiler is not finding the definition for the function calculatearea and giving error.
To solve this:
1) Write the definition for function calculatearea in the same file.
2) Make use of extern specifier with this function declaration and make sure that definition is present with the link library at the time of compilation.
3) As mentioned in the picture if the area.o have the definition of function calculatearea, then compile as below, this will generate a.out in linux:
gcc filename.c area.o

undefined reference to `__lzcnt16?

I have this code which I'm trying to run with GCC-TDM 1.7.4-2 using -msse4.2 (I tried msse4) with an error:
sse_lzcnt.c|7|warning: implicit declaration of function '__lzcnt16'|
sse_lzcnt.c|9|warning: too many arguments for format|
obj\Debug\sse_lzcnt.o||In function `main':|
sse_lzcnt.c|7|undefined reference to `__lzcnt16'|
An undefined reference is usually a linking error due to a missing lib file (.a ending) but the intrinsics headers don't need one?
I made sure the intrinsics headers are in the correct include directory. Heres the code,
#include <x86intrin.h>
#include <stdio.h>
int main()
{
unsigned short __X = 256;
unsigned short RESULT = __lzcnt16(__X);
printf("result: ", RESULT);
return 0;
}
You need to use the gcc command line option: -mlzcnt

Treat functions by name

Suppose you created a main() to deal with an exercise you asked your students.
Every student is supposed to write their own function, with the same API. And a single file will be created, with all functions and the main calling them.
Lets say: int studentname(int a, int b) is the function pattern.
One way I deal with it was using a vector of pointer to functions int (*func[MAX])(). But you need to fulfill the vector one by one func[0]=studentname;.
I wonder, is there a way a function can be called by its name somehow?
Something like: int student1(int a , int b), student2(), etc.
And in main somehow we could just call sscanf(funcname,"student%d",i); funcname();.
Do you have any other idea? Maybe
int studentname(int a, int b, char *fname)
{
strcpy(fname, "studentname");
Anything creative will do! :)
Thanks!
Beco
PS. I tried just a vector of functions, but C won't allow me! :)
int func[2]()={{;},{;}};
This way I could just give to each student a number, and voilá... But no way. It was funny though.
Edited: I'm using linux.
Edited 2: Thanks! I've accepted an answer that helped me, but I've also documented a complete example as an answer bellow.
Maybe a bit overcomplicating it, but spontaneous idea:
Compile all student source files into one shared library with the students' functions being exports.
Then enumerate all exposed functions, call and test them.
As an alternative:
Write a small tool that will compile all "student units" using a preprocessor define to replace a predefined function name with an unique name ("func1", "func2", etc.).
Then let the tool write a small unit calling all these functions while performing tests, etc.
And yet another idea:
Use C++ to write a special class template that's going to register derived classes in a object factory and just embed student's code using extern "C". Depending on the implementation this might look a bit confusing and overcomplicated though.
Then use the factory to create one instance of each and run the code.
Example for the approach with dlopen() and dlsym() (whether only one function per library or all - doesn't matter):
void *pluginlib = dlopen("student1.so", RTLD_NOW); // RTLD_NOW will load the file right away
if (!pluginlib)
; // failed to load
studentproc func = (studentproc)dlsym(pluginlib, "student1"); // this loads the function called "student1"
if (!func)
; // failed to resolve
func("hello world!"); // call the lib
dlclose(pluginlib); // unloads the dll (this will make all further calls invalid)
Similar to what #Jamey-Sharp proposed:
ask each student to provide .c file with entry function of a given name/signature
compile each .c into a shared library, named by the student name, or given whatever unique name. This step can be easily automated with make or simple script.
make a simple host application which enumerates all .so files in a given directory, and uses dlopen() and dlsym() to get to the entry point function.
now you can simply call each student's implementation.
BTW, that's how plug-ins are implemented usually, isn't it?
Edit: Here's a working proof of concept (and a proof, that each student can use the same name of the entry point function).
Here's student1.c:
#include <stdio.h>
void student_task()
{
printf("Hello, I'm Student #1\n");
}
Here's student2.c:
#include <stdio.h>
void student_task()
{
printf("Hello, I'm Student #2\n");
}
And here's the main program, tester.c:
#include <stdio.h>
#include <dlfcn.h>
/* NOTE: Error handling intentionally skipped for brevity!
* It's not a production code!
*/
/* Type of the entry point function implemented by students */
typedef void (*entry_point_t)(void);
/* For each student we have to store... */
typedef struct student_lib_tag {
/* .. pointer to the entry point function, */
entry_point_t entry;
/* and a library handle, so we can play nice and close it eventually */
void* library_handle;
} student_solution_t;
void load(const char* lib_name, student_solution_t* solution)
{
/* Again - all error handling skipped, I only want to show the idea! */
/* Open the library. RTLD_LOCAL is quite important, it keeps the libs separated */
solution->library_handle = dlopen(lib_name, RTLD_NOW | RTLD_LOCAL);
/* Now we ask for 'student_task' function. Every student uses the same name.
* strange void** is needed for C99, see dlsym() manual.
*/
*(void**) (&solution->entry) = dlsym(solution->library_handle, "student_task");
/* We have to keep the library open */
}
int main()
{
/* Two entries hardcoded - you need some code here that would scan
* the directory for .so files, allocate array dynamically and load
* them all.
*/
student_solution_t solutions[2];
/* Load both solutions */
load("./student1.so", &solutions[0]);
load("./student2.so", &solutions[1]);
/* Now we can call them both, despite the same name of the entry point function! */
(solutions[0].entry)();
(solutions[1].entry)();
/* Eventually it's safe to close the libs */
dlclose(solutions[0].library_handle);
dlclose(solutions[1].library_handle);
return 0;
}
Let's compile it all:
czajnik#czajnik:~/test$ gcc -shared -fPIC student1.c -o student1.so -Wall
czajnik#czajnik:~/test$ gcc -shared -fPIC student2.c -o student2.so -Wall
czajnik#czajnik:~/test$ gcc tester.c -g -O0 -o tester -ldl -Wall
And see it works:
czajnik#czajnik:~/test$ ./tester
Hello, I'm Student #1
Hello, I'm Student #2
I'd take a different approach:
Require every student to use the same function name, and place each student's code in a separate source file.
Write one more source file with a main that calls the standard name.
Produce a separate executable from linking main.c with student1.c, then main.c with student2.c, and so on. You might be able to use wildcards in a makefile or shell script to automate this.
That said, at least on Unix-like OSes, you can do what you asked for.
Call dlopen(NULL) to get a handle on the symbols in the main program.
Pass that handle and the function name you want to dlsym. Coerce the resulting pointer to a function pointer of the right type, and call it.
Here is an ugly preprocessor hack:
#Makefile
FILE_NAME=student
${FILE_NAME}: main.c
cc -Wall -DFILE_NAME=\"${FILE_NAME}.c\" -o $# main.c -lm
Teacher's main.c:
#include <math.h>
#include <stdio.h>
#include FILE_NAME
char *my_name(void);
double my_sin(double val);
int main(void)
{
double dd;
dd = my_sin(3.1415923563);
printf("%s: %f\n", my_name(), dd);
return 0;
}
Student's .c File:
#include <math.h>
char * my_name(void);
double my_sin(double val);
char * my_name(void)
{
return "Wildplasser-1.0";
}
double my_sin(double val)
{
return sin (val);
}
The trick lies i the literal inclusion of the student's .c file.
To avoid this, you could also use a different make line, like:
cc -Wall -o $# ${FILE_NAME}.c main.c -lm
(and remove the ugly #include FILENAME, of course)
Thanks you all. I've accepted an answer that gave me the inspiration to solve the question. Here, just to document it, is my complete solution:
File shamain.c
/* Uses shared library shalib.so
* Compile with:
* gcc shamain.c -o shamain -ldl -Wall
*/
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
int main(void)
{
void *libstud;
int (*student[2])(int, int);
char fname[32];
int i,r;
libstud = dlopen("./shalib.so", RTLD_NOW);
if (!libstud)
{
fprintf(stderr, "error: %s\n", dlerror());
exit(EXIT_FAILURE);
}
dlerror(); /* Clear any existing error */
for(i=0; i<2; i++)
{
sprintf(fname, "func%d", i);
*(void **) (&student[i]) = dlsym(libstud, fname); /* c99 crap */
//student[i] = (int (*)(int, int)) dlsym(libstud, fname); /* c89 format */
}
for(i=0; i<2; i++)
{
r=student[i](i, i);
printf("i=%d,r=%d\n", i, r);
}
return 0;
}
File shalib.c
/* Shared library.
* Compile with:
* gcc -shared -fPIC shalib.c -o shalib.so -Wall
*/
#include <stdio.h>
int func0(int one, int jadv)
{
printf("%d = Smith\n", one);
return 0;
}
int func1(int one, int jadv)
{
printf("%d = John\n", one);
return 0;
}
It is a while since I have used shared libraries, but I have a feeling you can extract named functions from a DLL/shlib. Could you create a DLL/shared library containing all of the implementations and then access them by name from the main?
Per #william-morris's suggestion, you might have luck using dlsym() to do a dynamic lookup of the functions. (dlsym() may or may not be the library call to use on your particular platform.)

C - Undefined symbols for architecture x86_64 when compiling on Mac OSX Lion

I'm getting some problems on compiling a very very simple name.c file on Mac OSX Lion.
Now, I started following Harvard CS50 course on cs50.net. I'm not totally new to programming but I was curious on how this course has been taught.
This is the source of name.c:
#include <stdio.h>
#include <cs50.h>
int
main(void)
{
printf("State your name:\n");
string name = GetString();
printf("O hai, %s!\n", name);
return 0;
}
As you can see, it requires this library: https://manual.cs50.net/CS50_Library.
Now, when I compile it, this happens:
Undefined symbols for architecture x86_64:
"_GetString", referenced from:
_main in name-vAxcar.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [name] Error 1
If I use the same GetString() cs50.c function inside my source file, it works perfectly:
#include <stdio.h>
#include <string.h>
#include <float.h>
#include <limits.h>
#include <stdbool.h>
#include <stdlib.h>
typedef char *string;
string GetString(void);
int
main(void)
{
printf("State your name:\n");
string name = GetString();
printf("O hai, %s!\n", name);
}
string
GetString(void)
{
// CODE
}
Why does this happen?
I installed the library as it says on the link above; I checked and both cs50.h and libcs50.a are respectively in /usr/local/include and /usr/local/lib.
Thank you in advance for your help.
The problem you encounter is in the linking stage, not compiling. You did not provide the implementation of GetString, only its declaration (through the .h file you #include).
To provide the implementation itself, you usually need to link against the library which includes it; this is usually done by the -l flag to g++. For example,
g++ file.cpp -lcs50
Your second sample code does link, because you manually (and explicitly) provide an implementation for GetString, though an empty one.

Resources