I am trying to execute basic code in C and C++ in Linux environment.
I am using eclipse to run it. Current project is created as C project.
All I am trying to do is to call a function from different file in same folder.
I have my main in sample.c, In main I would like to call function sum(int a, int b) in A.c. I was able to run it. But when I rewrite same function sum in A.cpp(a C++ template file) it throws linker error.
gcc -o "Test" ./sample.o
./sample.o: In function
main':/home/idtech/workspace/Test/Debug/../sample.c:19: undefined
reference to sum' collect2: ld returned 1 exit status make: * [Test]
Error 1
I need help in calling functions in C++ file from C file in same folder.
Please help me to solve this linker issue.
Thanks
Harsha
The C++ compiler mangles symbol names in order to encode type information. Typically, when writing C++ functions that should be exposed to C code, you'll want to wrap the function in an extern "C" { ... } block, like so (or just prefix it with extern "C" as #DaoWen pointed out):
A.cpp:
extern "C" {
int sum(int a, int b)
{
return a+b;
}
}
caller.c:
extern int sum(int a, int b);
...
int main() { sum(42, 4711); }
By marking a function as extern "C", you're sacrificing the ability to overload it, because different overloads are distinguishable only by their mangled symbol names, and you just requested that mangling be turned off! What it means is that you cannot do this:
extern "C" {
int sum(int a, int b) { return a+b; }
float sum(float a, float b) { return a+b; } // conflict!
}
Related
Lets say I have two (or more) c functions func1() and func2() both requiring a buffer variable int buff. If both functions are kept in separate files, func1.c and func2.c, How do I make it so that buff is accessible to only func1() and func2() and not to the calling routine(or any other routine).
Here is an example setup:
file func1.c:
/*func1.c*/
static int buff;
int *func1(int x)
{
buff = x;
return &buff;
}
file func2.c:
/*func2.c*/
static int buff;
int *func2(int x)
{
buff = x;
return &buff;
}
header header.h:
/*header for func1.c and func2.c*/
//multiple inclusion guard not present.
int *func1(int);
int *func2(int);
file main.c:
#include<stdio.h>
#include"header.h"
int main()
{
int *ptr;
ptr = func1(1);
printf("&buff = %p , buff = %d\n", ptr, *ptr);
ptr = func2(2);
printf("&buff = %p , buff = %d\n", ptr, *ptr);
return 0;
}
As expected, the output shows different memory locations for buff.
&buff = 0x55b8fd3f0034 , buff = 1
&buff = 0x55b8fd3f0038 , buff = 2
But I need only one copy buff, not more.
I could of course, put both functions in the same file, and define buff as static int but then I would lose the ability to compile the functions separately.
If I put int buff in a separate buff.c and declare it extern in func1.c and func2.c, but then it would be easily accessible by the calling routine(main in this case).
Basically, I need to create a library of functions that work on the same external object, that is accessible only to them. The calling routine may not need all the functions, so I do not want to put them in a single file and create unused code. But there must be only one copy of the object.
Please help on how I could do the same, if it is achievable.
The C standard does not provide a way to do this. It is usually done using features of compilers and linkers beyond the C standard. Here is an example using Apple’s developer tools on macOS. For options suitable to your environment, you should specify the build tools and versions you are using, such as whether you are using Apple tools, GNU tools, Microsoft tools, or something else.
With this in a.c:
#include <stdio.h>
int x = 123;
void a(void)
{
printf("In a.c, x is %d.\n", x);
}
and this in b.c:
#include <stdio.h>
extern int x;
void b(void)
{
printf("In b.c, x is %d.\n", x);
}
we compile the source files to object modules:
clang -c a.c b.c
and then link them to a new object module r.o while requesting that the symbol x (_x in the linker view) not be exported:
ld -r -o r.o -unexported_symbol _x a.o b.o
Then, if we have another source file c.c that attempts to use x:
#include <stdio.h>
extern int x;
extern void a(void);
extern void b(void);
int main(void)
{
a();
b();
printf("In c.c, x is %d.\n", x);
}
attempting to build an executable with it using clang -o c c.c r.o yields:
Undefined symbols for architecture x86_64:
"_x", referenced from:
_main in c-139a35.o
ld: symbol(s) not found for architecture x86_64
However, if we remove the two lines in c.c that refer to x, the build succeeds, and the program prints:
In a.c, x is 123.
In b.c, x is 123.
One typical approach to this problem is to give the global variable a name that begins with _.
That is, in func1.c you might write
int _mylib_buff;
And then in func2.c, of course, you'd have
extern int _mylib_buff;
Now, of course, in this case, _mylib_buff is technically an ordinary global variable. It's not truly "private" at all. But global variables beginning with _ are private "by convention", and I'd say this works okay in practice. But, obviously, there's nothing preventing some other source file from cheating and peeking at the nominally-private variable, and there's no way in Standard C to prevent one from doing so.
The other complication is that some identifiers beginning with _ are reserved to the implementation, and you're not supposed to use them in your own code. (That is, components of the implementation -- like your C compiler and C library -- have semi-global variables they're trying to hide from you, and they're typically using a leading _ to achieve this, also.) I'm pretty sure the rules say it's okay for you to define a global variable beginning with a leading underscore followed by a lower-case letter, but the rules are somewhat complicated, and I can never remember all the nuances. See questions 1.9 and 1.29 in the C FAQ list.
The answer is: It's not possible.
C has no way of saying "this variable may be used by source file x, y, z and not by any other sources files".
So if you want buff to be "private" to a number of functions, you'll have to put those functions in the same source file.
You need to define the non-static variable in one of the files for example:
int buff;
int *func1(int x)
{
buff = x;
return &buff;
}
in the header file declare it as extern:
/*header for func1.c and func2.c*/
//multiple inclusion guard not present.
extern int buff;
int *func1(int);
int *func2(int);
Include it in all other files:
/*func2.c*/
#include "header.h"
int *func1(int x)
{
buff = x;
return &buff;
}
If you do not want variable to be visible you need to create function which will get and set the "hidden" variable.
typedef enum
{
GET,
SET,
REF,
}OP_t;
#define CREATE(type, name) type getset##name(OP_t oper, type val, type **ref) \
{\
static type buff;\
switch(oper)\
{\
case GET:\
return buff;\
case SET:\
buff = val;\
break;\
case REF:\
if(ref) *ref = &buff;\
break;\
}\
return 0;\
}\
#define HEAD(type, name) type getset##name(OP_t oper, type val, type **ref)
#define GETVAL(name) getset##name(GET, 0, NULL)
#define SETVAL(name,val) getset##name(SET, val, NULL)
#define GETREF(name,ref) getset##name(REF, 0, ref)
is it possible to have 2 (or more) different implementations for the same function declared in a header file?
I'll give an example - let's say we have a header file called common.h and 2 source files called src1.c and src2.c.
common.h
//lots of common function declarations implemented in some file common.c
int func(int a, int b);
src1.c
#include "common.h"
int func(int a, int b)
{
return a+b;
}
src2.c
#include "common.h"
int func(int a, int b)
{
return a*b;
}
let's say that I want each of the source file to use its local version of func(). is it possible to do so?
Yes, but if you attempted to link your main program against both src1 and src2 you would encounter an error because it wouldn't know which definition to use.
Headers are just ways for other code objects to be aware of what's available in other objects. Think of headers as a contract. Contracts are expected to be filled exactly one time, not zero or multiple times. If you link against both src1 and src2, you've essentially filled the int func(int a, int b); contract twice.
If you need to alternate between two functions with the same signature, you can use function pointers.
If you want each source file to only use its local implementation of func, and no other module uses those functions, you can remove the declaration from the header and declare them as static.
src1.c
static int func(int a, int b)
{
return a+b;
}
src2.c
static int func(int a, int b)
{
return a*b;
}
By doing this, each of these functions is only visible in the module it is defined in.
EDIT:
If you want two or more functions to implement an interface, you need to give them different names but you can use a function pointer to choose the one you want.
common.h
typedef int (*ftype)(int, int);
int func_add(int a, int b);
int func_mult(int a, int b);
src1.c
#include "common.h"
int func_add(int a, int b)
{
return a+b;
}
src2.c
#include "common.h"
int func_mult(int a, int b)
{
return a*b;
}
Then you can chose one or the other:
ftype func;
if (op=='+') {
func = func_add;
} else if (op=='*') {
func = func_mult;
...
}
int result = func(value1,value2);
If you compile it with each src[x].c, you'll be able to use it in any function of your .c
You can decide to not expose the function implementation to other translation units. In c, use keyword static before the function signature right where you implement the function (see code below); In C++, you can also use unnamed namespaces. By doing so, the linker will not give you an error, and each translation unit will use it's own implementation:
Suppose the following two translation units main.c and another.c. Both have their (private) implementation of int function(a,b), such that they yield different results when calling it:
extern void someOtherFeature();
static int function (a,b) {
return a+b;
}
int main(){
int x = function(1,2);
printf("main: function(1,2)=%d\n", x);
someOtherFeature();
}
// another.c:
#include <stdio.h>
static int function (a,b) {
return a*b;
}
void someOtherFeature() {
int x = function(1,2);
printf("someOtherFeature: function(1,2)=%d\n", x);
}
Output:
main: function(1,2)=3
someOtherFeature: function(1,2)=2
However, if both translation units exposed their implementations (i.e. both omitted keyword static, then the linker would report an error like duplicate symbol _function in:....
If you want each source file to use a local version of func, just put it in an unnamed namespace:
For example src1.C:
namespace
{
int func(int a, int b)
{
return a+b;
}
}
Then each source file will use its own version. You don't need to declare it in the header.
Note that your original code with the definitions at global namespace and declared in the header violates the one definition rule (two function definitions for the same name must always have the same definition), invoking undefined behavior, no diagnostic required.
I wrote a program in C and I want to use C++ library in this code, I though that I will be able to compile the C in g++ since C++ built in top of C. However, I couldn't do that and the main error was because in one part of the code I wrote a function to read data from input file, before the main function. That worked well in C compiler but not in Cpp compiler.
Below is some of the error messages I got, so I'd like to get general comments and points to take into consideration when use c and cpp interchangeably
error : ‘get_inputs’ was not declared in this scope
error: use of parameter outside function body before ‘]’ token
Following program compiles in C with a warning such as: 'bar' undefined; assuming extern returning int
void foo()
{
bar(5);
}
int bar(int x)
{
return x*2;
}
If you want this to compile in C++ you must declare bar before you use it:
int bar(int x); // forward declaration
void foo()
{
bar(5);
}
int bar(int x)
{
return x*2;
}
Even in C it's good practice to use forward declarations and to enable all compiler warnings otherwise the error in following program will slip through:
void foo()
{
bar(); // calling bar without argument....
}
int bar(int x)
{
return x*2; // ... will result in an undefined value for x here
}
I am trying to use a Visual C++ dll in a VB.NET windows application, both created in VS2010. In the Windows project I can successfully add the dll to my references but only functions without pointer arguments are usable in the program and visible in the object browser. I borrowed a simple example I found and changed one of the function arguments to be a pointer.
header file:
// TestDLL.h
using namespace System;
namespace MathFuncs
{
public ref class MyMathFuncs
{
public:
static double Add(double *a, double B);
static double Subtract(double a, double B);
static double Multiply(double a, double B);
static double Divide(double a, double B);
};
}
cpp file
// TestDLL.cpp
// compile with: /clr /LD
#include "TestDLL.h"
namespace MathFuncs
{
double MyMathFuncs::Add(double *a, double B)
{
return *a + b;
}
double MyMathFuncs::Subtract(double a, double B)
{
return a - b;
}
double MyMathFuncs::Multiply(double a, double B)
{
return a * b;
}
double MyMathFuncs::Divide(double a, double B)
{
if (b == 0)
{
throw gcnew DivideByZeroException("b cannot be zero!");
}
return a / b;
}
}
The dll compiles successfully with no warnings. When I reference the dll in a simple windows form I get the error:
"Error 1 'Add' has a return type that is not supported or parameter types that are not supported."
If I remove the pointer the dll works fine. From other forums I thought the calling convention might be a problem and tried using __stdcall but I got another error saying reference classes can't use __stdcall.
I also tried not referencing the dll and instead declaring the dll functions from a module in the windows application. I got an error saying "entry point not found" which I think is because C++ decorates the function name. I tried dumpbin.exe/EXPORTS "dll PATH" but it would not show the decorated function names. I have also tried creating an module definition file and using extern "c" although I most likely didn't use them properly. All solutions I have found to these problems have been for unmanaged C++ but do not work for managed Visual C++.
I would rather be able to reference the dll because it seems simpler. Any insight would be greatly appreciated.
Change your definition to :
double Add(double % a, double b)
{
return a + b;
}
This compiles as ByRef and works:
C language does not use name mangling like C++. This can lead to subtle bugs, when function prototype is declared differently in different files. Simple example:
/* file1.c */
int test(int x, int y)
{
return y;
}
/* file2.c */
#include <stdio.h>
extern int test(int x);
int main()
{
int n = test(2);
printf("n = %d\n", n);
return 0;
}
When compiling such code using C compiler (in my case gcc) no errors are reported. After switching to C++ compiler, linking will fail with error "undefined reference to 'test(int)'". Unfortunately in practice this is not so easy - there are cases when code is accepted by C compiler (with possible warning messages), but compilation fails when using C++ compiler.
This is of course bad coding practice - all function prototypes should be added to .h file, which is then included in files where function is implemented or used. Unfortunately in my app there are many cases like this, and fixing all of them is not possible in short term. Switching to g++ is also not at option, I got compilation error quite fast.
One of possible solutions would be to use C++ name mangling when compiling C code. Unfortunately gcc does not allow to do this - I did not found command line option to do this. Do you know if it is possible to do this (maybe use other compiler?). I also wonder if some static analysis tools are able to catch this.
Using splint catches these kinds of errors.
foo.c:
int test(int x);
int main() {
test(0);
}
bar.c:
int test(int x, int y) {
return y;
}
Running splint:
$ splint -weak foo.c bar.c
Splint 3.1.2 --- 20 Feb 2009
bar.c:1:5: Function test redeclared with 2 args, previously declared with 1
Types are incompatible. (Use -type to inhibit warning)
foo.c:4:5: Previous declaration of test
Finished checking --- 1 code warning
~/dev/temp$ cat > a.c
int f(int x, int y) { return x + y; }
~/dev/temp$ cat > b.c
extern int f(int x); int g(int x) { return f(x + x); }
~/dev/temp$ splint *.c
Splint 3.1.2 --- 03 May 2009
b.c:1:12: Function f redeclared with 1 arg, previously declared with 2
Types are incompatible. (Use -type to inhibit warning)
a.c:1:5: Previous declaration of f
Finished checking --- 1 code warning
~/dev/temp$