logo
down
shadow

Is it valid to treat an extern global as const when the definition is not const?


Is it valid to treat an extern global as const when the definition is not const?

By : Wayne Clark
Date : November 14 2020, 04:51 PM
seems to work fine It's clearly undefined as the declarations don't match. As you noted, const int and int aren't compatible types. A diagnostic is required only if they appear in the same scope.
It isn't safe in practice either, consider
code :
$ cat test1.c
#include <stdio.h>

extern const int n;
void foo(void);

int main(void) {
    printf("%d\n", n);
    foo();
    printf("%d\n", n);
}
$ cat test2.c
int n;
void foo(void) { ++n; }
$ gcc -std=c99 -pedantic test1.c test2.c && ./a.out
0
1
$ gcc -O1 -std=c99 -pedantic test1.c test2.c && ./a.out
0
0
int my_real_variable;
const int *const my_variable = &my_real_variable;
#define my_variable (*(const int *)&my_variable)
const int *const my_variable_ptr = &(int){ 12 };


Share : facebook icon twitter icon
global extern const clarification

global extern const clarification


By : user2579477
Date : March 29 2020, 07:55 AM
will help you Is declaring extern const or just extern the same thing in a header file? Also will both give external linkage? , This one is correct,
code :
//globals.h

extern const std::string foo; //Consistent
global const variable definition - access through extern in c++

global const variable definition - access through extern in c++


By : user7289944
Date : March 29 2020, 07:55 AM
I hope this helps . As for me it looks like a compiler bug. Constant variable i is not defined It is only declared in main.cpp. As for variable i in module.cpp then it has internal linkage and shall not be accessible outside the module.
Relative to your addition to the original post then the compiler has nothing common with this situation. It is linker that checks whether there are duplicate external symbols. I think it decided that if one variable has qualifier const and other has no it then there are two different variables. I think that it is implementation defined whether the linker will issue an error or not. Moreover it can have some options that could control the behaviour of the linker in such situations.
When sharing a const across files using extern, why is extern needed on the definition?

When sharing a const across files using extern, why is extern needed on the definition?


By : karven
Date : March 29 2020, 07:55 AM
it should still fix some issue Page 60 of C++ Primer 5th edition talks about sharing const variables across files like so , According to the standard,
Should immutable global objects be declared as 'const my_result_t BLAH;' or 'extern const my_result_t BLAH;'?

Should immutable global objects be declared as 'const my_result_t BLAH;' or 'extern const my_result_t BLAH;'?


By : user3197347
Date : March 29 2020, 07:55 AM
this will help Const namespace scope variables should have default internal linkage, so it is correct to write const my_result_t RESULT_XXX; in the header:
code :
// ErrorCode.h

#pragma once
#include <string_view>
/** Ultra-lightweight type for returning the success/error status from a function. */
class my_result_t
{
public:
    /** Default constructor, creates a my_result_t indicating success */
    constexpr my_result_t() : _errorString{} {/* empty */ }

    /** Constructor for returning an error-result */
    constexpr my_result_t(const char* s) : _errorString(s) {/* empty */ }

    /** Returns true iff the result was "success" */
    constexpr bool IsOK() const { return (_errorString.data() == nullptr); }

    /** Returns true iff the result was an error of some type */
    constexpr bool IsError() const { return (_errorString.data() != nullptr); }

    /** Return a human-readable description of the result */
    constexpr std::string_view GetDescription() const { return _errorString.data() ? _errorString : "Success"; }

    /** Returns true iff the two objects are equivalent */
    constexpr bool operator ==(const my_result_t& rhs) const
    {
        return _errorString.data() ? ((rhs._errorString.data()) && 
            (_errorString == rhs._errorString)) : (rhs._errorString.data() == nullptr);
    }

    /** Returns true iff the two objects are not equivalent */
    constexpr bool operator !=(const my_result_t& rhs) const { return !(*this == rhs); }

private:
    std::string_view _errorString;
};

inline constexpr my_result_t RESULT_SUCCESS{};
inline constexpr my_result_t RESULT_OUT_OF_MEMORY("Out of Memory");
inline constexpr my_result_t RESULT_ACCESS_DENIED("Access Denied");
inline constexpr my_result_t RESULT_BAD_ARGUMENT("Bad Argument");
inline constexpr my_result_t RESULT_FILE_NOT_FOUND("File not Found");

// main.cpp

#include "ErrorCode.h"
#include <iostream>

inline my_result_t SomeFunction()
{
    FILE* fp = fopen("some_file.txt", "r");
    if (fp)
    {
        fclose(fp);
        return RESULT_SUCCESS;  // success!
    }
    else return RESULT_FILE_NOT_FOUND;
}

int main() {
    std::cout << SomeFunction().GetDescription();
    return 0;
}
constexpr bool strings_equal(char const* a, char const* b) {
    return a == nullptr ? (b == nullptr) : (b != nullptr && std::string_view(a) == b);
}
Why is my extern const double incompatible with double function parameter, but my extern const int is compatible with in

Why is my extern const double incompatible with double function parameter, but my extern const int is compatible with in


By : Double
Date : March 29 2020, 07:55 AM
This might help you Nevermind, after scrutinizing my code a little closer I found that I had accidentally left in some brackets in the header file, so it said "extern const double d_const()", which obviously it shouldn't. Removing those brackets fixed the problem. I can't believe I missed that despite double-checking the syntax over and over but there you go. for the answers nonetheless!
Related Posts Related Posts :
  • Program works but outputs trailing garbage values
  • Letting 2 pointer pointing to same address
  • Different ways to print the two-dimensional array's contents
  • C Programming : Confusion between operator precedence
  • C code inside a loop not being executed
  • C - Weird symbols
  • C - Get pointer adress to string
  • how to start a function using a Struct?
  • Trying to tweak sscanf() to ignore \n and \t
  • How to find the inverse of a Rectangular Matrix in C using GSL
  • sizeof() showing different output
  • How to select/read/copy values after specific character in a string
  • Jump from bootloader generates exception
  • Array dropping values, picks up garbage
  • Swig: Syntax error in input(3)
  • multiple definition and making sure function is correctly written
  • MD4 openssl core dumped
  • Undefined-Behavior at its best, is it -boundary break? -bad pointer arithmetic? Or just -ignore of aliasing?
  • Why am i getting problem3.c:20:23: error: expected expression before ‘int’?
  • Right Justified Zero filled String in C
  • C Function with parameter without type indicator still works?
  • How to transmit data from an interrupt handler to an user application?
  • Why do I get the error "bash: ./a.out: Permission denied" when I execute a C program in Linux mint 15
  • syntax of sigchld and its declaration
  • error using g_idle_add() in C++, same thing works in C
  • why if else or nested if else are called single statement in C
  • How do I interpret this printf in C
  • load the functions of a shell script without executing it
  • Is FilterSendNetBufferLists handler a must for an NDIS filter to use NdisFSendNetBufferLists?
  • How to write to flash memory using inline assembly?
  • More Return Statements vs. More Indentation
  • How to show an image on a PictureBox from resource?
  • Having malloced some memory,I could't calculator the proper size of the memories I malloced.I don't know why
  • What is the main difference between integer pointer and character pointer?
  • Why are some functions declared extern and header file not included in source in Git source code?
  • what is the use of fflush(stdin) in c programming
  • Is it safe to return file File descriptor locally allocated from another function In C
  • Changing undefined values of an array
  • What does an empty parameter list mean?
  • using strtol on a string literal causing segmentation fault
  • Same structure objects memory overlap?
  • C-Linux-Any way to pass command "history" to Linux shell?
  • Using #define in defining string size C
  • How to use thread pool and message queues in Multithreaded Matrix Multiplication?
  • Can't find how to select path to run a C program
  • Automatic variable in C not initialized but given fixed value within loop
  • main() function defined without return type gives warning
  • Output of following code with integer, float, char variable
  • why buffer memory allocation error in opencl
  • Why am I getting this error during run-time?
  • Strange behaviour of the pow function
  • task in increment , decrement , printf() , why these are evaluated in this manner in C
  • 28 extra bytes in bss
  • Waiting for multiple events without polling
  • Why are my variables reporting as "undeclared identifier" when compiling?
  • Correct AddNode function but somehing happens when I printf
  • When I traverse in the splay tree, then now which one is root?
  • Data type conversion in Postfix evaluation
  • No output in terminal (Head First C)
  • Data writes over after realloc
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org