Same function name, different C files - c

I have two tools in C to parse data from a database to an XML file or a normal text file. Both files contain the same function names but with different implementations, so I am working on merging them both in a single tool and the output type (XML or text) will depend on the input from the user.
So, the problem is having same function (and struct) names but with different implementations. How can I overcome this situation without having to rename everything because that will lead to a mess.
Thank you.

If you have to use both sets of types and functions in the same program at the same time, and if those type and function names have to be visible outside of their enclosing source file(s)1 (i.e., you have a .h file with those type definitions and function declarations), then you must rename at least one set of them. No other choice. C doesn't provide user-definable namespaces2, so anything with external linkage must have a globally unique name.
If those type and function names don't have to be visible outside of their source file3 (i.e., they don't have to be called by a function defined outside of their source file), then you can declare the functions as static - that will limit their visibility to the enclosing source file. If the type names are local to the source file (you haven't put them in a .h that must be included by another source file), then they won't be exported.
If you only need to use one set or the other, but which set isn't known until runtime, you can put each in a shared library and then load the correct one at runtime (using dlopen on the *nix side - not sure what the Windows equivalent would be).
A fourth option would be to switch to C++ and wrap each set in a unique namespace; depending on what you're doing that may be the fastest option.
The function names have what is known as external linkage.
C has four namespaces - label names, tag names, struct and union member names, and all other identifiers (variable names, function names, typedef names, enumeration constants, etc.). Those namespaces are fixed, and you can't create any more.
The function names have either internal or no linkage.

You can enclose each of the function definitions in a different namespace. You won't have to change intra-namespace function calls, but you will have to preface inter-namespace function calls with the "other" namespace.

Related

Can I declare a function in a C source file without declaring it in the header file?

I'm only asking because I have an assignment that includes writing a function to find the inverse of a matrix. I did this using Cramer's rule and a determinant function which I added to my header file.
When I submit, however, it uses the header file we were given. So I'm trying to find out if I can somehow still use my determinant function without it being declared in the header file.
Yes, you certainly can include the declaration in your source file. Make sure that the declaration comes before the usage of the function.
Why you have to declare the function(s) in your source file if you have the respective header? Just include the header file which will/ should contain the declaration of function.
Yes, you can declare your function(s) in the source file as well which isn't in problem in small projects but it will add complexity if you somehow expands or share your project in future, its a good practice to keep the interfaces (in this case, header files) separate from the implementations (.c files).
Yes, you can declare a (global) function in a source file instead of a header.
No, you should not declare such functions in source files — each such function should be declared in one header, and that header should be used wherever the function is used (and where it is implemented, of course).
Note that if you declare the function in a source file (other than the file where the function is implemented) and do not use a header, then it becomes much more of an exercise if you ever need to alter the interface to the function — you have to search files to find it, rather than just modifying the header. Depending on the change, you may need to do more, but the old declarations scattered around the code base won't change magically, and the compiler won't spot that the definition has changed, and all hell will break loose (probably) because you have different parts of the code using different interfaces to the same function. C does not have type-safe linkage, unlike C++.
Header files are the glue that hold programs together and ensure correct operation. If you skip using a header, you lose the reliability provided by a common header which checks that the source code implementing the function matches the source code using the function.
Clearly, any function only used in a single file should be made static and should not be declared in any header. In case of doubt, make the function (and any file scope variables) static until you've a proven need to access them from another source file. And then you should ensure you define and use a header file to declare those functions (and variables, if you are really sure you need them) and use the header in the implementation source file and in the consumer source files. It may or may not be a new header; the information must be in an appropriate header.
Applying these diatribes to your problem
The header you were given constrains you, but the code outside your source file won't be using your determinant function, so it should be static and defined (and maybe declared) only in your source file — it should not be defined in the header since the judging code won't pay any attention to it. Your code that implements the interface required by the assignment can, and will, call your determinant function. But that will be in the source file, along with the determinant function. You need to declare the determinant function if it is used (called) before it is defined. If it is defined before it is used, you do not need a separate declaration, but no harm is done if you create one.
Side note
The rules for inline functions are similar to those outlined above. If need so be, you can create a static inline definition in a header file, and use that wherever the function is used. There are other ways to handle them — be cautious and make sure you understand what you're doing (and search on SO to find the answers; they're there).

Same name structure with different definition in C

Is it allowed to use same name structure with different definitions in 2 different c files in the same project. For eg.
File1.c
typedef struct
{
unsigned int unVar;
} abc;
File2.c
typedef struct
{
int var;
} abc;
abc is used in both the files. When i compile these file as part of same project there are no errors, but i want to understand whether this is correct usage.
6.7.2.1 Structure and union specifiers
The presence of a struct-declaration-list in a struct-or-union-specifier declares a new type,
within a translation unit.
Types are defined only within a translation unit, a .c file in this case.
There is no problem with defining two types with the same name in two different translation units.
However those two types are not compatible unless they follow the rules described in 6.2.7., p1. The types you defined are not compatible.
This is type definition. It is local for each .c file and there is no reason to get error. Definitions have to be made in header files and then you will not have such problem.
Symbols' names (variables', functions) must be unique within a translation unit.
A translation unit is a basic compilation unit for C and C++. It consists of a source file, along with all included files (either directly or indirectly).
In your case, you have two independent source files, each defining a struct; but they "can't see" each other, as they are within separate translation units.
You might get into trouble, however, during linking, if there are multiple symbols with the same name across target linking objects (as long as these symbols are exported, which can be modified with static keyword).
It is a correct usage to define two structs with the same name in two different *.c files because they are only valid for the current scope in the *.c where it is defined.
But further I would not recommend to do this to avoid any confusion of you and any other developer who has to work with two types of the same name that do doing other things.
Each definition is local to the file in which it appears. Since you compile the files separately, the compiler only sees one at a time. The linker binding the object files together does not verify type consistency, it only resolves symbols by name.
If you want to pass a st_localAscdData or a pointer to a st_localAscdData to a function from a different module, you must ensure consistency between the types declared in the different modules. This is the purpose of header files. Shared declarations belong in header files, that must be included in all modules that share a given type or function.
Global type consistency is not enforced by the C language, nor C++ to some extend, it is the programmers responsibility. Coding rules are guidelines to help programmers avoid pitfalls from this shortcoming.
You expect a redefined error (which will happen with cpp compiler) but it won't happen in C compiler.
This issue not just happen with structure but also with all kinds of variable.
I have make a question for this and have some detail and quality answer.
Does C have One Definition Rule like C++?

Why won't C compile if two separate source files in the same workspace share function names?

I'm using eclipse indigo, gcc and cdt in a project. If two functions in separate source files share names (regardless of return type or parameters), eclipse flags a redefinition error. This isn't a huge issue regarding this project given I can easily rename these functions, and I'm well aware of wrappers if it were. Although this isn't a critical issue, it does make me think I'm not understanding the c build process. What occurs during the build process in which a program structure like this would cause issue?
Here's some more info. on the situation, and where my understanding is so far -- not necessary to answer the question, although there must be a hole in my understanding.
In this case, the two functions are intended to be used only locally, as such their prototypes are not given in the .h interface, and for the sake of my point, neither are defined 'static'.
Neither of these source files are being included anywhere in the project, so they shouldn't be sharing any compilation units. With that in consideration, I would have assumed that the neither source file is aware of the presence of the other, and the compiler would have no problem indexing the two functions, as the separate files would allow for proper distinguishing between the two during linking -- so long as they weren't included in the same compilation unit.
I noticed that statically defining either instance of the function declaration removes the error. I remember reading at some point that every function not declared static is global -- although given these functions are not a part of the .h interface, the practical example in which including the .h interface doesn't allow for the including program to reference all .c functions would indicate "hiding" these functions would be of no issue.
What am I overlooking?
Some insight would be greatly appreciated, thanks!
This is the concept of "linkage". Every function and variable in C has a linkage type, one of "external", "internal", and "none". (Only variables can have no linkage.)
Functions have external linkage by default, which means that they can be called by name from any compilation unit (where "compilation unit" roughly means one source file and all the headers it includes). This can be expressed explicitly by declaring them extern, or it can be overridden by declaring them static. Functions declared static have internal linkage, meaning they can be referenced by name only from other functions in the same compilation unit.
No two external functions anywhere in the same program can have the same name, regardless of header files, but static functions in different compilation units may have the same name. A static function may have the same name as an external function, too -- then the name resolves to the static function within its compilation unit, and to the external function elsewhere. These restrictions make sense, for otherwise it would be possible for a function call to be ambiguous.
Header files don't factor into the linkage equation at all. They are primarily a vehicle for sharing declarations, but a function's linkage depends only on how it is declared, not on where.
I leave discussion of variables' linkage for another time.
It doesn't matter whether one source module includes headers for another. Header files only contain declarations for the purpose of local functions being able to find functions in other modules. It doesn't mean that functions not declared don't exist from the perspective of that module.
When everything gets linked together, anything not specifically defined to be local to one source module (i.e. static) has to have a unique name across all linked components.
remember reading at some point that every function not declared static is global
Having understood this you got the main point and reason for the behaviour observed.
.h files are not known to the linker, after pre-processing there are only translation units left (typically a .c file with all includes merged in), from which .o files are compiled.
There are no interfaces on language level in C.
Neither of these source files are being included anywhere in the project, so they shouldn't be sharing any compilation units.
Declare those functions as static. This is the only way to "hide" a function from the linker "inside" a translation unit.
C doesn't "mangle" function names the way C++ or Java do (since C doesn't support function polymorphism).
For example, in C++, the functions
void foo( void );
void foo( int x );
void foo( int x, double y );
have their names "mangled" into the unique symbols1
_Z3fooid
_Z3fooi
_Z3foov
which is how overloaded function/method calls are disambiguated at the machine level.
C doesn't do that; instead, the linker sees two different function definitions using the same symbol and yaks because it has no way to disambiguate the two.
1. This is what happens on my system, anyway

Where should non-interface function prototypes be placed?

I've read repeatedly that header files should include all the declarations that other files will need to use the source code. Suppose then that you have a function that is not used directly by other source files (a non-interface function, in other words). Should its prototype be placed at the top of the .c file, since it will not be used by other files? Or should it be placed in the header files with all the other functions, in order to fully summarize the functions present in the .c file in one place?
The header contains the interface information (whatever is needed for the outside world to use the functionality in the "module" -- e.g. the .c file). So internal functions (that are not used from outside), do not go into the header
In the .c file it depends on organization
some people like to list all internal function declaration at the top, so they are in one place.
others rely on ordering so a function is defined by the time it is used (in another function); and only forward declare it if necessary (e.g. recursive functions that call each other)
If the function is not used by other .c files, it should not have a prototype in a header file. You should give it the static modifiler, and place
the prototype at the top of the (only) .c file where it is used.
If it's reasonable and possible, you can just define the function before all the
functions that call it, so you don't even need a prototype.
Yes, the prototype of a private function should be placed in the same .c file as the function. The header defines the external interface.
Rather than forward declarations, some programmers prefer to define the functions in the order they're used so prototypes are unnecessary. Of course, you can't do this if two or more functions call each other.
My personal preference is to declare all of the functions first, so you'll have an overview of the file.
If you have functions that are used within a single module (a small set of files that together implement a functional unit), it's perfectly reasonable to create a second module-specific header file. All of the files in the module—but no external source files—will #include it.
Given that header files are essentially the only way to declare an external interface in C, things not part of that interface should not be in the header file.
C being what it is, sometimes this is not practical, because the internal view of an externally visible definition needs to refer to it; in this case you might place it in the header but protected by a #define that clearly indicates its internal provenance, and likewise use #ifdef to select the internal vs. external version of the definition that requires it. (You will see this in system header files often.) It's better to try to avoid this, though.
Putting at all the function declarations in the prototype syntax at the top of the .c source file is good style in my opinion. It serves also to document you source code for the reader.
You don't want to put the declarations in the .h header file as you would unnecessarily expose the internals of your programs.
Oh, and don't forget to add the static specifier in the function declarations.

How to deal with duplicated function name within C?

I have a little project in which I named two same name function in two different source file, but while I building the project, the compiler failed with 'func_name already defined in filename.obj'.
Why could not I have two functions with the same name in two different source files? I thought the function should be local to the source file only if when we declared it in the header file will it become global.
And except for changing the filename, are there any other elegant solution to duplicated function name in the C programming language?
In C, a function has global scope by default. To restrict its scope, use the static keyword to make it private to a the module.
The role of the header file is just to publicize the function along with its signature to other modules.
All global names must (with some caveats) be unique. This makes sense because that name is what is used by the linker to connect a function call to implementation of the function itself.
Names with static and local scope need only be unique within their scope.
Whether some thing is declared in header file or in source file makes absolutely no difference for the compiler. In fact, the compiler proper knows absolutely nothing about any "header files", since header files are embedded into source files by so called preprocessor, which does its work before the compiler proper. By the time the source files (with embedded header files) get to the actual compiler, there's no way to tell what was there originally and what was inserted from header files. The source file with all the header files embedded into it is called translation unit. I.e. the compiler proper works with translation units, not with some "source" or "header" files.
In C language all objects and functions declared at file scope have external linkage by default, which means that they are global, unique for the entire program. So, you thought incorrectly. Functions are not local to one source file only.
If you want to make a function (or an object) local to a single translation unit, you have to take some explicit steps. You have to declare it as static. Declaring it as static will give it internal linkage, which essentially means that it becomes internal to its translation unit.
Declaring your functions static will only work if both of them really have to be local to their own translation units. If this is not the case, i.e. if at least one of the functions should be a globally accessible (linkable) function, then you have no other choice but to rename one of functions.
Why could not I have two function with the same name in two differenct source file?
Because the linker needs to know which is meant when you reference it.
Imagine that a.h and b.h both declare my_function(). The compiler generates code for both. Now, imagine that c.c calls my_function() - how does the linker know which of the two versions of the function should be called?
Declare the function static to make it local to the file. In C, every identifier name must be unique.
The elegant solution is namespaces introduced in C++. The solution, if there are few calls to func_name is take one, rename it and recompile.
Something hackerous but quick solution might be this:
//In one of the two source files and any file that calls it
//if your functions is something like this
//void func_name(int) { ... }
//Add the following line
#define func_name SOME_UNIQUE_FUNC_NAME

Resources