Skip to content

Accessing C++ variables in separate .c/.cpp files

Hello,

I have created ports in C++ and would like to use it separate .c files.

I have a complex function, but to test out the functionality, I am using addition function in a separate file and would like to use the variable defined above.

Error during compilation

I can use the variable in the program file without any issues, However I need to use the variable in the function itself.

I apologize if I am missing something basic here. We need to use separate files for our project and a way to use the C++ variables across the functions. Please help.

Comments

  • edited September 2022

    I think this is a general C/C++ question, rather than anything specific to PLCnext Technology.

    For a start the port variable is not static, so it needs to be qualified with a reference to the program instance (object). To avoid the problem of getting an object reference, one solution would be to declare a static variable in the program header file that could be assigned in the function. But that won't be a port variable.

    Another possibility is to add another argument to the addition function, so you can pass a reference to the port variable when the function is called in the Execute method.

    If you can give more details on the requirements in this case, e.g. the relationship between the program and the function, maybe other solutions can be suggested.

  • edited September 2022

    try StateMachinesProgram::iAState = sum;

    https://en.cppreference.com/w/cpp/language/namespace


    Also make note of private and public variables: https://en.cppreference.com/w/cpp/language/access

Sign In or Register to comment.