I have a lot of unused macros in my code.
So, I am wondering.. If a macro is unused, does it takes up memory space in your program?
The type of macros I have are just the basic ones.
Example:
#define TEST_ID 0
Macros will be expanded during preprocessing phase so they don't exist in your program. They just take some space in your source code.
Edit:
In response to Barmar's comment, I did some research.
MSVC 2012: In debug build (when all optimizations are disabled, /Od), adding lines of macros won't cause the growth of the size of your program.
GCC: does provide a way to include macro in debugging information as long as you compile your program with a specific flag. See here. (I didn't know that before myself. Thank you, #Barmar, #Sydius)
No, doesn't takes space until is used, for this two pieces of code:
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("%d %s\n", argc, argv[0]);
return 0;
}
and
#include <stdio.h>
#define TEST_ID 0
int main(int argc, char *argv[])
{
printf("%d %s\n", argc, argv[0]);
return 0;
}
The ASM generated with gcc -S is the same.
macro is replaced by preprocessor before compilng start.
if you define a macro, and doesn't use it, the compiler will never see it.
Related
This is my code:
#include <stdio.h>
#include <sys/statfs.h>
int main(int argc, char** argv)
{
struct statfs64 mystatfs64;
statfs64("/", &mystatfs64);
return 0;
}
But I get this error:
error: storage size of ‘mystatfs64’ isn’t known
warning: implicit declaration of function ‘statfs64’; did you mean ‘statfs’?
On the man page it says: The glibc statfs() and fstatfs() wrapper functions transparently deal with the kernel differences.
So I changed my code to:
#include <stdio.h>
#include <sys/statfs.h>
int main(int argc, char** argv)
{
struct statfs mystatfs;
statfs("/", &mystatfs);
return 0;
}
It now compiles but sizeof(((struct statfs*)0)->f_blocks) is 4 so I can't handle big file systems.
I also tried to define __USE_LARGEFILE64 and __USE_FILE_OFFSET64 without any success.
The __USE_* macros are for glibc's internal header features.h to define, not you. If you try to define them yourself, they won't work.
You are instead supposed to define macros from a different set, called the "feature test macros" or "feature selection macros" and partially specified by POSIX. The most up-to-date and coherent documentation of the full set of feature test macros understood by glibc is in the Linux manpages: feature_test_macros(7). Note that most of these macros must be defined before you include any system headers.
The best way to write the code you're trying to write is to use the _FILE_OFFSET_BITS feature test macro to make normal off_t, fsblkcnt_t, etc. be 64 bits wide:
#define _FILE_OFFSET_BITS 64
#include <inttypes.h>
#include <stdio.h>
#include <sys/statfs.h>
int main(int argc, char** argv)
{
struct statfs mystatfs;
statfs("/", &mystatfs);
printf("block count: %"PRIu64"\n", mystatfs.f_blocks);
return 0;
}
If you don't want to add this #define to the top of every .c file of your program, you may instead be able to add -D_FILE_OFFSET_BITS=64 to your compilation options in your Makefile or equivalent (for instance, add it to CPPFLAGS if you're using for Make's standard built-in compilation rules).
You also have the option of using _LARGEFILE64_SOURCE to gain access to the xxx64 functions and types, but this is discouraged by the C library maintainers: note what it says about it in the manpage I linked above
_LARGEFILE64_SOURCEExpose definitions for the alternative API specified by the LFS (Large File Summit) as a "transitional extension" to the Single UNIX Specification. (See ⟨https://www.opengroup.org/platform/lfs.html⟩.) The alternative API consists of a set of new objects (i.e., functions and types) whose names are suffixed with "64" (e.g., off64_t versus off_t, lseek64() versus lseek(), etc.). New programs should not employ this macro; instead _FILE_OFFSET_BITS=64 should be employed.
(boldface: my emphasis)
As clang-format is a tool to only reformat code, is it possible that such formatting can break working code or at least change how it works? Is there some kind of contract that it will/can not change how code works?
We have a lot of code that we want to format with clang-format. This means, many lines of code will change. Not having to review every single line of code that only changed due to a clang-format would be a big simplification of this process.
I would say that clang-format will not change how code works. On the other hand I am not 100% sure, if this can be guaranteed.
Short answer: YES.
The clang-format tool has a -sort-includes option. Changing the order of #include directives can definitely change the behavior of existing code, and may break existing code.
Since the corresponding SortIncludes option is set to true by several of the built-in styles, it might not be obvious that clang-format is going to reorder your includes.
MyStruct.h:
struct MyStruct {
uint8_t value;
};
original.c:
#include <stdint.h>
#include <stddef.h>
#include "MyStruct.h"
int main (int argc, char **argv) {
struct MyStruct s = { 0 };
return s.value;
}
Now let's say we run clang-format -style=llvm original.c > restyled.c.
restyled.c:
#include "MyStruct.h"
#include <stddef.h>
#include <stdint.h>
int main(int argc, char **argv) {
struct MyStruct s = {0};
return s.value;
}
Due to the reordering of the header files, I get the following error when compiling restyled.c:
In file included from restyled.c:1:
./MyStruct.h:2:5: error: unknown type name 'uint8_t'
uint8_t value;
^
1 error generated.
However, this issue should be easy to work around. It's unlikely that you have order-dependent includes like this, but if you do, you can fix the problem by putting a blank line between groups of headers that require a specific order, since apparently clang-format only sorts groups of #include directives with no non-#include lines in between.
fixed-original.c:
#include <stdint.h>
#include <stddef.h>
#include "MyStruct.h"
int main (int argc, char **argv) {
struct MyStruct s = { 0 };
return s.value;
}
fixed-restyled.c:
#include <stddef.h>
#include <stdint.h>
#include "MyStruct.h"
int main(int argc, char **argv) {
struct MyStruct s = {0};
return s.value;
}
Note that stdint.h and stddef.h were still reordered since their includes are still "grouped", but that the new blank line prevented MyStruct.h from being moved before the standard library includes.
However...
If reordering your #include directives breaks your code, you should probably do one of the following anyway:
Explicitly include the dependencies for each header in the header file. In my example, I'd need to include stdint.h in MyStruct.h.
Add a comment line between the include groups that explicitly states the ordering dependency. Remember that any non-#include line should break up a group, so comment lines work as well. The comment line in the following code also prevents clang-format from including MyStruct.h before the standard library headers.
alternate-original.c:
#include <stdint.h>
#include <stddef.h>
// must come after stdint.h
#include "MyStruct.h"
int main (int argc, char **argv) {
struct MyStruct s = { 0 };
return s.value;
}
For sure it can change how your code works. And the reason is C program can view some properties of its source code. What I'm thinking about is __LINE__ macro, but I'm not sure there are no other ways.
Consider 1.c:
#include <stdio.h>
int main(){printf("%d\n", __LINE__);}
Then:
> clang 1.c -o 1.exe & 1.exe
2
Now do some clang-format:
> clang-format -style=Chromium 1.c >2.c
And 2.c is:
#include <stdio.h>
int main() {
printf("%d\n", __LINE__);
}
And, of course, output has changed:
> clang 2.c -o 2.exe & 2.exe
3
Since clang-format affects only whitespace characters, you can check that files before and after clang-formating are identical up to whitespaces. In Linux/BSD/OS X you can use diff and tr for that:
$ diff --ignore-all-space <(tr '\n' ' ' < 2.c ) <(tr '\n' ' ' < 1.c)
1.c:
#include <stdio.h>
int main() {printf("Hello, world!\n"); return 0;}
2.c:
#include <stdio.h>
int main() {
printf("Hello, world!\n");
return 0;
}
Output of diff command is empty, meaning that files 1.c and 2.c are identical up to whitespaces.
As Karoly mentioned in his comment, note that in ideal conditions you still have to check spaces that matters, e.g. string literals. But in the real world I believe this test is more than enough.
clang-format reformatted ASM code in a project because we effectively did this:
#define ASM _asm
ASM {
...
}
yes
it will not break the working flow
the system has the config switch:
"C_Cpp.clang_format_sortIncludes": false,
but it not work, i don't know what is wrong...
my version is:ms-vscode.cpptools-0.13.1
this is my solution:
for the stable working flow ,use the grammar:
// clang-format off
...here is your code
// clang-format on
It can break your code, if you use special constructs in your code and your settings for formatting.
Inline Assembler
If you normally compile your code with gcc and make use of gcc-style inline assembler, clang-format will very likely break the naming of register variables, as it sees the %-character as an operator.
asm_movq(%[val2], %%mm0)
will be reformatted as
asm_movq(% [val2], % % mm0)
which will no longer compile.
Constructing a Path in a macro
If you build up a path using macros without using strings, clang-format again will see the '/' character as an operator and will put spaces around it.
Boost e.g. uses a construct like this:
# define AUX778076_PREPROCESSED_HEADER \
BOOST_MPL_CFG_COMPILER_DIR/BOOST_MPL_PREPROCESSED_HEADER
to construct a path to a header file. The '/' is not an operator here, but as it is not inside a string, clang-format treats it as an operator and puts spaces around it, creating a different path.
The include of the header file will obviously fail.
Conclusion
Yes, clang-format can break your code. If you are using very specific constructs that are edge cases or outside of the language standard or simply extensions of your very specific compiler (which is not clang), then you will need to check the changes made by clang-format. Otherwise you risk getting hidden errors.
I imagine it would not, given that it is built on clang's static analysis, and therefore has knowledge of the structure of code itself, rather than just a dumb source code formatter that operates on the text alone(one of the boons of being able to use a compiler library). Given that the formatter uses the same parser and lexer as the compiler itself, I'd feel safe enough that it wouldn't have any issue spitting out code that behaves the same as what you feed it.
You can see the source code for the C++ formatter here: http://clang.llvm.org/doxygen/Format_8cpp_source.html
I am looking for a way to find the name of the executable file which runs it. meaning that if I have a file called program which runs something I would like to get its name.
Using __FILE__ does not suite me since I need the executable name not the C files name which contains the code.
I am wondering if there is a gcc macro which can help me or a built in function which I couldn't find.
EDIT:
Also using argv[0] is not appropriate since I need to call the function not only inside main.
And passing the argv[0] parameter to all the functions that might need this parameter also isnt acceptable since it will be used in the entire system (I need to hash by it).
int main(int argc,char* argv[])
{
printf("%s",argv[0]);
return 0;
}
The first argument(argv[0]) contains the name of the program which is being run.
The standard definition for main() in C is:
int main(int argc, char **argv)
argv[0] contains the name of the program as executed.
From main, pass argv[0] to wherever you might need the program's name.
Or if a lot of functions need it and you want to avoid passing it around too much, assign it to a global variable.
You asked for macros as a solution, but they are expanded at compile time. And since the name of the executable file can be changed after compilation, what you want cannot be determined at compile time, so macros are out of question.
Often remembering argv[0] from main will be quite sufficient.
If this is not the case -- for example if you're a shared library, or if you worry that your caller started you with a faked argv[0] (this is possible but unusual), you can, on POSIX-compliant systems with a mounted /proc, use readlink to resolve /proc/self/exe and get a path to the main binary of the running process:
#include <limits.h>
#include <unistd.h>
// Note that readlink does not null-terminate the result itself. This
// is important if the link target contains null bytes itself, I suppose,
// but it means that you have to take care that the null-terminator is
// placed yourself if you're going to use the file name as a string.
char buf[PATH_MAX] = { 0 };
readlink("/proc/self/exe", buf, PATH_MAX);
And on Windows, there is the GetModuleFileName function:
#include <windows.h>
TCHAR buf[MAX_PATH];
GetModuleFileName(NULL, buf, MAX_PATH);
The startup name is given via main()'s argv[0] and can be considered constant.
So why not make it available through out the program using a global reference to it.
progname.h
#ifndef PROGNAME_H
#define PROGNAME_H
extern char * progname;
#endif
main.c
#include "progname.h"
char * progname = NULL;
int main(int argc, char ** argv)
{
progname = argv[0];
...
}
Access it from any where like so
module1.c
#include <stdio.h>
#include "progname.h"
void f(void)
{
printf("progname='%s'\n", progname ?progname :"<not set>");
}
I saw redefine function here using macro in c. So I am interesting is it possible to redefine main function?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv)
{
printf("Original main function\n");
return 0;
}
int _main(int argc, char **argv)
{
printf("New Original main function\n");
return main(argc, argv);
}
#ifdef DEBUG
#define main(argc, argv) _main(argc, argv)
#endif
Code compiled with out any problem but I am getting:
Original main function
So I am wondering why it does not work? When I use same techniques for malloc and free functions it works perfect. So what is wrong?
Why I want to do something like this? I want to do some code before main function will be executed. Is it possible in this way? if not is there are some other way?
P.S.: Sorry I did not mention in question. I am using gcc in Ubuntu OS. If you are down voting please give a reason in comments. You comments is very useful to my further development.
If you want to change entry point of your program, you don't need play with defines. You can use linker's -e option for that:
gcc -Wl,-e,__main ...
Please note extra underscore. Depending on some options, the symbol name can be different.
If your question is really: "can i execute code before main?" Then the answer is an emphatic YES.
Since you are using GCC, you can use function attributes (http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html) to mark a function as a constructor.
void pre_main_function (void) __attribute__ ((constructor));
A useful example can be found at http://www.geeksforgeeks.org/functions-that-are-executed-before-and-after-main-in-c/
EDIT
The following syntax can also be used:
__attribute__ (( constructor(n) ))
where n specifies the priority, allowing you to mark multiple functions to be executed before main whilst giving you control over the execution order ( the lower the value of n, the earlier the function is executed.
Your #define does not change the main function at all - it is a macro preprocessor.
The only effect of your #define will be to change the call to main in _main into a recursive call to _main(). But since _main is not called, this is dead code. This is what your code looks like after the preprocessor has run...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv)
{
printf("Original main function\n");
return 0;
}
int _main(int argc, char **argv)
{
printf("New Original main function\n");
return _main(argc, argv); /* recursive call due to macro replace */
}
This then leads to the next question - which is why redefine main at all? If you want some entirely different code to run on debug simply declare main as
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv)
{
#ifdef DEBUG
return debugApp( argc, argv);
#else
return productionApp( argc, argv);
#endif
}
N.B Just because you can do something doesn't mean you should do it. :-)
/*you cannot change anything from here below*/
main()
{
exit(0);
}
/*you cannot change anything from here up*/
This was asked during an interview.
I was told to print something on console.
anybody?
Really surprised that nobody posted this yet:
#include <stdio.h>
#if 0
/*you cannot change anything from here below*/
main()
{
exit(0);
}
/*you cannot change anything from here up*/
#endif
int main()
{
printf("Hello, World!");
return 0;
}
Prints at runtime and no undefined behavior whatsoever.
weird question...
int main(void)
{
printf("hello");
return 0;
}
#define main int lol
/*you cannot change anything from here below*/
main()
{
exit(0);
}
/*you cannot change anything from here up*/
#include <stdio.h>
#define exit(c) return puts("foobar"),0
over main
One implementation defined way would be to use the pragma directives to print during compilation.
#pragma message "Compiling " __FILE__ "..."
Or, you could do this with some macros and a printf (but not without introducing UB in some aspect or the other) at runtime.
#define exit(x) printf("Hello, world!")
int main() {
exit(0);
return 0; /* if pre-C99 */
}
#include <stdio.h>
#pragma message("Some foobar")
#error This is an error message
int main()
{
exit(0);
}
I think the interviewer wanted to know if you're aware of the #error directive ... just my 2 cents.
Most answers involve the #define c-preprocessor instruction to change what the program means. Most compilers also support something like
#pragma startup foo()
details depend on the compiler vendor. You can make code run BEFORE main(*) is called that way.
#define exit(x) (printf("Bye"))
int main(int argc,char* argv)
{
exit(0);
getchar();
return 0;
}
Solution 1.
This works without any preprocessor directives in cl and gcc, although I've not tested to make sure I'm not using any extensions:
#include <stdio.h>
static void exit() {
printf("Hello world");
}
/*you cannot change anything from here below*/
main()
{
exit(0);
}
/*you cannot change anything from here up*/
I think it's valid but I can't remember if masking a standard library function is allowed or not.
Solution 2
As several other answers have specified, you can use preprocessor directives, eg:
#define main or exit to be something that calls ifdef
use #if 0 to prevent the existing code being compiled
using #pragma message or #error to print a message at compile time
using #pragma startup to use a different function as main or to run start-up code before main.
Solution 3
If your compiler supports any C++ features in addition to C, there are many answers:
Declare a class with a constructor and a static variable of that type
Put the existing "main" function into a separate namespace (or class definition) and write a different global main
Solution 4
I also looked for any way of forcing a run-time error (stack overflow, out of memory, null dereference, tc), which would normally cause the program to print something, but couldn't find any way that didn't involve running extra code, in which case the extra code might as well be printf.
If you interpreted the question to mean you could not or were not allowed to edit the file by commenting out /* */ or using #ifdef _COMMENT_ME_OUT__ #endif respectively above and below the section you are not allowed to edit and then introducing a new main, then you should give an answer of using another .c file.
If you cannot find a workaround to edit that file, then use a different c file.